基於你的previous question was tagged with sql server的事實,我猜你需要sql server語法。
爲了得到結果,您需要同時使用UNPIVOT
和PIVOT
函數。未轉位將採用TCount
和Count
列並將它們轉換爲行,然後PIVOT
將採用dates
並將它們轉換爲列。
如果你提前知道時間的價值,那麼你可以硬編碼查詢:
select *
from
(
select date, value, col
from yourtable
unpivot
(
value
for col in (tcount, count)
) unpiv
) src
pivot
(
max(value)
for date in ([2013-02-06], [2013-02-12],
[2013-02-21], [2013-02-27])
) piv;
見SQL Fiddle with Demo
但是,如果你有數目不詳的日期,那麼你將需要動態SQL:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ',' + QUOTENAME(convert(varchar(10), Date, 120))
from yourtable
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT col, ' + @cols + ' from
(
select convert(varchar(10), Date, 120) date,
value, col
from yourtable
unpivot
(
value
for col in (tcount, count)
) unpiv
) src
pivot
(
max(value)
for date in (' + @cols + ')
) p '
execute(@query)
見SQL Fiddle with Demo
兩者的結果是:
| COL | 2013-02-06 | 2013-02-12 | 2013-02-21 | 2013-02-27 |
--------------------------------------------------------------
| COUNT | 35 | 23 | 54 | 12 |
| TCOUNT | 3500 | 4000 | 1000 | 5000 |
**什麼**數據庫系統/產品/ RDBMS ?? – 2013-02-12 21:44:17
可能重複的[SQL Server動態PIVOT查詢?](http://stackoverflow.com/questions/10404348/sql-server-dynamic-pivot-query) – 2014-04-24 18:03:16