5

假设我有下表:

1) tblScore

============================ 
Date      VendorID     Score 
============================ 
12/09/01  12001        A     
12/09/01  12001        A     
12/09/01  12002        B     
12/09/02  12003        C     
12/09/02  12003        A     
12/09/03  12001        C     
============================ 

我有这个查询:

SELECT ts.VendorID, ts.Score, COUNT(*)
FROM trxscore ts
GROUP BY ts.VendorID, ts.Score
ORDER BY ts.VendorID, ts.Score

但是如何显示表格:

===========================
VendorID    A    B    C
===========================
12001       2    0    1
12002       0    1    0 
12003       1    0    1
===========================

而且,是否有可能从文本中获得平均值?即,VendorID 12001应该得到 A 的平均值。谢谢...

4

1 回答 1

8

试试这个,

SELECT  VendorID,
        SUM(CASE WHEN Score = 'A' THEN 1 ELSE 0 END) totalA,
        SUM(CASE WHEN Score = 'B' THEN 1 ELSE 0 END) totalB,
        SUM(CASE WHEN Score = 'C' THEN 1 ELSE 0 END) totalC
FROM    tableName
GROUP BY VendorID

SQLFiddle 演示

于 2012-10-01T02:18:10.820 回答