您沒有指定您正在使用的RDBMS。您可以支點使用聚合函數與CASE
的表達在所有數據庫中的數據:
select id, name,
sum(case when month = 'December2012' then "count" end) December2012,
sum(case when month = 'January2013' then "count" end) January2013
from yourtable
group by id, name
見SQL Fiddle with Demo
如果您正在使用SQL Server 2005+或Oracle 11g,那麼你可以使用PIVOT
功能:
select *
from
(
select id, name, month, [count]
from yourtable
) src
pivot
(
sum([count])
for month in (December2012, January2013)
) piv
參見SQL Fiddle with Demo。
在SQL Server中,如果month
的值是未知的,那麼你可以使用類似的動態SQL這樣的:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ',' + QUOTENAME(month)
from yourtable
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT id, name,' + @cols + ' from
(
select id, name, month, [count]
from yourtable
) x
pivot
(
sum([count])
for month in (' + @cols + ')
) p '
execute(@query)
見SQL Fiddle with Demo
所有版本產生的結果是:
| ID | NAME | DECEMBER2012 | JANUARY2013 |
-------------------------------------------
| 1 | David | 500 | 400 |
| 2 | Rob | 320 | 280 |
你正在使用什麼RDBMS? –
[你有什麼嘗試?](http://whathaveyoutried.com) –