2017-04-13 159 views
0

我在SQL Server中使用日期和性別數據統計SQL Server的數據透視表Help101

WC   Gender Cnt 
----------------------- 
2017-01-02 M 84617 
2017-01-02 F 54896 
2017-01-09 M 60120 
2017-01-09 F 40173 
2017-01-16 M 56387 
2017-01-16 F 41164 

我有這種格式的數據,我需要把它改造成

WC   M  F 
-------------------------- 
02/01/2017 84617 54896 
09/01/2017 60120 40173 
16/01/2017 56387 41164 

回答

1

使用條件聚集:

select 
    wc 
    , M = max(case when gender = 'M' then Cnt end) 
    , F = max(case when gender = 'F' then Cnt end) 
from t 
group by wc 

使用pivot()

select 
    wc 
    , M 
    , F 
from t 
    pivot (max(cnt) for gender in (m,f)) as p 

都返回:

+------------+-------+-------+ 
|  wc  | M | F | 
+------------+-------+-------+ 
| 2017-01-02 | 84617 | 54896 | 
| 2017-01-09 | 60120 | 40173 | 
| 2017-01-16 | 56387 | 41164 | 
+------------+-------+-------+ 

Rextester演示:http://rextester.com/ITC17758

+0

非常感謝它的工作。愛你。 –

+0

@ArijitGanguly樂於幫忙! – SqlZim

0

沒有透視需要。你可以用幾個連接來做到這一點...

SELECT a.wc, t1.cnt, t2.cnt 
FROM (SELECT DISTINCT wc FROM tablename) a 
INNER JOIN tablename t1 ON t1.wc = a.wc AND t1.gender = 'M' 
INNER JOIN tablename t2 ON t2.wc = a.wc AND t2.gender = 'F'