我有两个专栏' Team'和' WLD'在mysql数据库中。 WLD代表Won,Lost,Drawn,并且每行数百包含W,L或D.我想输出一个SELECT中列中有多少W,L和D。
如果我用其中一个做到这一点就可以了:
SELECT Team, COUNT(WLA) AS Won FROM ResultsTest WHERE WLA = 'W'
然而,只要我添加另一个COUNT语句,它就会开始抱怨:
SELECT Team, COUNT(WLA) AS Won
FROM ResultsTest
WHERE WLA = 'W',
COUNT(WLA) AS Lost FROM ResultsTest WHERE WLA = 'L'
我哪里错了?
答案 0 :(得分:0)
您需要GROUP BY
子句才能完成数据聚合。最重要的是,如果您不想为胜负创建两个不同的提取并加入它们,您可以在以下情况下使用二进制和:
SELECT Team,
COUNT(*) AS Matches,
SUM(CASE WHEN WLD = 'W' THEN 1 ELSE 0 END) AS Wins,
SUM(CASE WHEN WLD = 'L' THEN 1 ELSE 0 END) AS Losses,
SUM(CASE WHEN WLD != 'W' AND WLD != 'L' THEN 1 ELSE 0 END) AS Draws
FROM ResultsTest
GROUP BY Team
答案 1 :(得分:-1)
谢谢你们。有用。节省了我很多时间:
SELECT Team,
COUNT(*) WLD,
SUM(CASE WHEN WLD = 'W' THEN 1 ELSE 0 END) AS Won,
SUM(CASE WHEN WLD = 'L' THEN 1 ELSE 0 END) AS Lost,
SUM(CASE WHEN WLD = 'D' THEN 1 ELSE 0 END) AS Drawn
FROM ResultsTest
GROUP BY Team