[英]SQL Count occurrences in a column and calculate total of another
我有一个以这种格式产生的派生表:
THENAME | THESTATUS | THECOST
----------------------------------
name1 | statusX | cost1.1
name1 | statusX | cost1.2
name2 | statusZ | cost2.1
name2 | statusZ | cost2.1
name3 | statusY | cost3.1
(...)
nameN | status(X,Y,Z) | cost
每个 nameN 将始终具有相同的状态,但成本会有所不同。 我试图想出一个看起来像这样的结果
Status Groups | Count of Names | Total Cost of Group
X 2 10
Y 5 20
Z 4 5
基本上,显示每个状态的总成本和每个状态包含的项目数。
去寻找类似的东西
SELECT
thestatus,
COUNT(DISTINCT thestatus),
SUM(thecost)
FROM THETABLE
GROUP BY thestatus
不起作用,我在想是否有可能同时对两列进行分组。
编辑 - https://www.db-fiddle.com/f/bB1RSy8GV35FGEi3Lr1Tqw/0
编辑 - 不确定它是 MySQL 的版本还是什么,但在示例数据中,我认为它可以正常工作,但在实际查询中却没有。 重新创建整个模式和整个查询是不可能的,但也许它是别的东西......
SELECT
DISTINCT THESTATUS as 'Status groups',
COUNT(THENAME) AS 'Count of Names',
SUM(THECOST) as 'Total Cost of Group'
FROM THETABLE GROUP BY THESTATUS
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.