MySQL GroupBy and Shows it horizontally

旧时模样 提交于 2020-08-27 09:11:07

问题


Supposed that I have table below:

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     
============================ 

I have this query:

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

But how to show the table like:

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

And, is it possible to get an average from a text? i.e., VendorID 12001 should get the average of A. Thanks...


回答1:


Try this,

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



来源:https://stackoverflow.com/questions/12666796/mysql-groupby-and-shows-it-horizontally

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!