[英]How to COUNT different values without adding to GROUP BY
I have a data set that contains a name for every "job" record, and whether the job passed or failed. 我有一个数据集,其中包含每个“作业”记录的名称,以及该作业是否通过。 I want to show the Name, number of jobs, how many passed, and how many failed in one row.
我想在一行中显示名称,作业数量,通过的数量以及失败的数量。
I am grouping the name and using COUNT on the name to count the total number of jobs, which works fine, but I can't show how many passed and how many failed without adding them to the GROUP BY clause causing the data to separate again. 我正在对名称进行分组,并在名称上使用COUNT来计数作业总数,这很好,但是如果不将其添加到GROUP BY子句中导致数据再次分离,就无法显示已通过的数量和失败的数量。
SELECT I.Name, Count(I.Name) As NumberOfJobs,
CASE WHEN WI.resultTypeID = 1 THEN COUNT(WI.resultTypeID) END AS [Passed],
CASE WHEN WI.resultTypeID = 2 THEN COUNT(WI.resultTypeID) END AS [Failed],
FROM DB.DBO.People AS I
INNER JOIN DB2.dbo.Jobs AS WI ON I.JOBID = WI.JOBID
GROUP BY I.Name, wi.resultTypeID
+-----------+-----------+--------+--------+
| Name | NumofJobs | Passed | Failed |
+-----------+-----------+--------+--------+
| Dale Test | 2 | 2 | NULL |
| Dale Test | 2 | NULL | 2 |
+-----------+-----------+--------+--------+
This is what happens when I add ResultTypeID to the GROUP BY, but I want this: 当我将ResultTypeID添加到GROUP BY时会发生这种情况,但是我想要这样做:
+-----------+-----------+--------+--------+
| Name | NumofJobs | Passed | Failed |
+-----------+-----------+--------+--------+
| Dale Test | 4 | 2 | 2 |
+-----------+-----------+--------+--------+
Is there anyway to do this? 反正有这样做吗?
You want conditional aggregation. 您需要条件聚合。 The
case
expression is an argument to the aggregation function: case
表达式是聚合函数的一个参数:
SELECT I.Name, Count(*) As NumberOfJobs,
SUM(CASE WHEN WI.resultTypeID = 1 THEN 1 ELSE 0 END) AS [Passed],
SUM(CASE WHEN WI.resultTypeID = 2 THEN 1 ELSE 0 END) AS [Failed],
FROM DB.DBO.People I INNER JOIN
DB2.dbo.Jobs WI
ON I.JOBID = WI.JOBID
GROUP BY I.Name;
I am guessing that wi.resultTypeID
is not NULL
, so I replaced the COUNT()
with SUM()
because I prefer SUM()
in this case. 我猜
wi.resultTypeID
不是NULL
,所以我用SUM()
替换了COUNT()
,因为在这种情况下我更喜欢SUM()
。
You don't need to group your query by wi.resultTypeID
. 您无需按
wi.resultTypeID
对查询进行wi.resultTypeID
。
simply remove wi.resultTypeID
from group by statement and put it inside aggregate function: 只需从group by语句中删除
wi.resultTypeID
并将其放入聚合函数中即可:
SELECT I.Name, Count(I.Name) As NumberOfJobs,
SUM(CASE WHEN WI.resultTypeID = 1 THEN 1 ELSE 0 END) AS [Passed],
SUM(CASE WHEN WI.resultTypeID = 2 THEN 1 ELSE 0 END) AS [Failed],
FROM DB.DBO.People AS I
INNER JOIN DB2.dbo.Jobs AS WI ON I.JOBID = WI.JOBID
GROUP BY I.Name
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.