2011-08-20 83 views
1

我正在改進執行MySQL查詢的一段PHP代碼。查詢目前生產這樣一組結果:改進基本的SQL查詢 - 對結果進行分組

id summary status date_submitted last_updated value 
48 test case 1 30 1313755157 1313755252 Low Yield 
48 test case 1 30 1313755157 1313755252 28BK 
48 test case 1 30 1313755157 1313755252 Yield 
48 test case 1 30 1313755157 1313755252 3 
48 test case 1 30 1313755157 1313755252 1 
48 test case 1 30 1313755157 1313755252 n/a 

Value將永遠是不同的,但所有其他字段將是相同的值。我要變換的上面這個樣子

id summary status date_submitted last_updated value1, value2, value3, value4, value5 
48 test case 1 30 1313755157 1313755252  Low Yield 28BK Yield 3 1   n/a 

所以每個值都有自己列了。我不認爲我需要粘貼獲得第一個結果的大量查詢嗎?我想人們可以把結果當成一張表格,並從中提出一個查詢?如果有要求,我會發布原始查詢。

非常感謝。

+0

只是爲了幫助討論,這些操作在SQL Server環境中通常被稱爲PIVOT/UNPIVOT。 –

回答

1

你不能做到這些,但你可以做一個逗號分隔值的列表。看到這個問題:

How to use GROUP BY to concatenate strings in MySQL?

你會寫是這樣的:

SELECT 
    id, 
    summary, 
    status, 
    date_submitted, 
    last_updated, 
    GROUP_CONCAT(value SEPARATOR ',') as values 
FROM 
    table 
GROUP BY 
    id, 
    summary, 
    status, 
    date_submitted, 
    last_updated 

在這種情況下,值將取值「低產量,28BK,產量,3,1,N /一個」。

0

你可以使用一組情況時與列別名:

Select Case value = 'Low Yield' then 'Low Yield' else NULL END as LowYieldCol, 
Case value = 'Yield' then 'Yield' else NULL END as YieldCol, 
...... 

+0

嘿,像'低收益'這樣的東西可能會像100個不同的東西。抱歉! – ale