2014-04-03 42 views
0

奇怪的問題......我知道。所以讓我解釋一下。選擇查詢,總結行並將其作爲列返回

這裏是我的文字表

quota  | metric_id 
    100  |  1 
    20  |  2 
    100  |  15 
    50  |  1 
    30  |  2 
    20  |  15 
    50  |  1 
    200  |  2 
    10  |  15 

我想要的SELECT語句將返回以下

id_1 |  id_2  |  id_15 
    200  |  250  |  130 

下面是數據是:

Column `id_1` is sum of the 3 rows where `metric_id=1` 
Column `id_2` is sum of the 3 rows where `metric_id=2` 
Column `id_15` is sum of the 3 rows where `metric_id=15` 

任何幫助?

+0

轉換'列'id_1'是3行的總和,其中'metric_id = 1''爲SQL,你很高興去。 – Shomz

+0

[How to pivot a MySQL entity-attribute-value schema]可能的重複(http://stackoverflow.com/questions/649802/how-to-pivot-a-mysql-entity-attribute-value-schema) – Vatev

+0

'metric_id'是靜態的嗎?只有這3個值? –

回答

0

一個可行的方法:

SELECT SUM(quota * (metric_id = 1)) AS id_1, 
     SUM(quota * (metric_id = 2)) AS id_2, 
     SUM(quota * (metric_id = 15)) AS id_15 
FROM Table1 

Demo。這很簡單:metric_id = N對於那些屬性等於N的行是1,對於其他所有行是0。乘以quota乘以1即爲quota,乘以0-0,其餘部分對於SUM()函數是容易的。

+0

感謝您的幫助。這正是醫生訂購的 – codeNinja

0

試試這個

select SUM(case when metric_id = 1 then quota END) id_1 
     SUM(case when metric_id = 2 then quota END) id_2 
     SUM(case when metric_id = 15 then quota END) id_15 
FROM Table1