我在DB2数据库中有一个表,如下所示:
StatusCode | IsResolved | IsAssigned
ABC | Y |
ABC | N |
ABC | |
ADEF | Y |
ADEF | | Y
我希望以如下方式获取数据:
StatusCode |Count of Status Code| Count of Resolved with value Y| Count of Assigned With value Y
ABC | 3 | 1 | 0
ADEF | 2 | 1 | 1
我可以使用groupBy
获取状态代码的计数,但我不知道如何获取已在同一查询中解析和分配的计数数据。
Query: select statusCode,count(statusCode) from table group by statusCode
任何人都可以帮我解决如何获取已解决和已分配的计数吗?
问题解决方案:Christian和JPW:解决方案是使用sum(案例IsResolved当' Y'然后1其他0结束)
答案 0 :(得分:4)
尝试使用
select statusCode, count(statusCode),
sum(case IsResolved when 'Y' then 1 else 0 end),
sum(case IsAssigned when 'Y' then 1 else 0 end)
from table
group by statusCode
答案 1 :(得分:3)
获得所需结果的一种方法是使用条件聚合(使用谓词来确定如何聚合数据),如下所示:
select
StatusCode,
count(*) as "Count of Status Code",
sum(case when IsResolved = 'Y' then 1 else 0 end) as "Count of Resolved with value Y",
sum(case when IsAssigned = 'Y' then 1 else 0 end) as "Count of Assigned With value Y"
from your_table
group by StatusCode;
案例表达式构造(case ... when ... then .. end
)是ANSI SQL标准的一部分,因此这适用于任何兼容的数据库。
答案 2 :(得分:0)
您可以使用SUM()和CASE
来实现此目的SELECT
statusCode,
COUNT(statusCode)
,SUM(CASE WHEN IsResolved='Y' THEN 1 ELSE 0 END) Resolved
,SUM(CASE WHEN IsAssigned='Y' THEN 1 ELSE 0 END) Assigned
FROM [Questions] GROUP BY statusCode
以下是相关问题:Sql Server equivalent of a COUNTIF aggregate function
答案 3 :(得分:0)
我认为之前的答案使用SUM聚合,因为缺少值的值是未知的。如果缺少值是NULL值,则每个值都可以编码为COUNT,其效果与SUM相同。
如果OP中给出的“我有一个表”中的缺少值是NULL值,和如果[有效数据符合或实际存在存在] 的CHECK约束 IN ('Y','N')
的ColumnNames,然后类似于其他答案,但执行COUNT并使用NULLIF作为CASE表达式的简化/特殊情况效果:
select
statuscode as "StatusCode"
, count(*) as "Count of Status Code"
, count(nullif(isResolved,'N')) as "Count of Resolved with value Y"
, count(nullif(isAssigned,'N')) as "Count of Assigned with value Y"
from so39705143
group by statuscode
order by statuscode