假设我有下表:
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 的平均值。谢谢...
最佳答案
试试这个,
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 Demo
关于MySQL Group By 并水平显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12666796/