所以我有一个像下面那样的表结构。
以下是条件:
我想要输出以下结构:
我写了一段代码,但不知怎的,它没有给我想要的结果。 我使用Case何时对Classification1进行分类,然后运行子查询以取出Count。 如果有不同的方法以及如何在分组声明中合并案例,请提供帮助。
我写了这个查询:
SELECT
CASE
WHEN UPPER(CM1.Classification1) IN ('A', 'C','G') THEN 'X'
WHEN UPPER(CM1.Classification1) IN ('B', 'F') THEN 'Y'
WHEN UPPER(CM1.Classification1) IN ('D', 'E') THEN 'Z'
ELSE 'Undefined' END AS New_Classification,
(SELECT
COUNT(CASE
WHEN UPPER(CM2.Classification1) IN ('A', 'C','G') THEN 'X'
WHEN UPPER(CM2.Classification1) IN ('B', 'F') THEN 'Y'
WHEN UPPER(CM2.Classification1) IN ('D', 'E') THEN 'Z'
ELSE 'Undefined' END)
FROM TABLE1 CM2 WHERE
CM2.Condition1 IS NOT NULL AND
CM2.Condition2 IS NOT NULL AND
CM2.Condition3 IS NOT NULL AND
CM2.Condition4 IS NOT NULL AND
CM1.ID=CM2.ID) AS Count_of_tagged,
(SELECT
COUNT(CASE
WHEN UPPER(CM3.Classification1) IN ('A', 'C','G') THEN 'X'
WHEN UPPER(CM3.Classification1) IN ('B', 'F') THEN 'Y'
WHEN UPPER(CM3.Classification1) IN ('D', 'E') THEN 'Z'
ELSE 'Undefined' END)
FROM TABLE1 CM3 WHERE
(CM3.Condition1 IS NULL OR
CM3.Condition2 IS NULL OR
CM3.Condition3 IS NULL OR
CM3.Condition4 IS NULL) AND
CM1.ID=CM2.ID) AS Count_of_untagged
FROM TABLE1 CM1
答案 0 :(得分:1)
你不应该需要一个子查询,作为我提出的出发点:
SELECT CASE Classification1
WHEN 'A' THEN 'X'
WHEN 'B' THEN 'Y'
WHEN 'C' THEN 'X'
WHEN 'D' THEN 'Z'
WHEN 'E' THEN 'Z'
WHEN 'F' THEN 'Y'
WHEN 'G' THEN 'X'
END new_classification,
SUM(
Condition1 IS NOT NULL AND
Condition2 IS NOT NULL AND
Condition3 IS NOT NULL AND
Condition4 IS NOT NULL /* 1 for true, 0 for false */
) tagged_count,
SUM(
Condition1 IS NULL OR
Condition2 IS NULL OR
Condition3 IS NULL OR
Condition4 IS NULL
) untagged_count,
FROM table_name
GROUP BY new_classification
答案 1 :(得分:0)
可以尝试使用以下sql并告诉我这是否是您需要的
select
CASE
WHEN classification ='A' THEN 'X'
WHEN classification ='B' THEN 'Y'
WHEN classification ='C' THEN 'X'
WHEN classification ='D' THEN 'Z'
WHEN classification ='E' THEN 'Z'
WHEN classification ='F' THEN 'Y'
WHEN classification ='G' THEN 'X'
END as classification,
sum(case when condition1 is not null and condition2 is not null and condition3 is not null and condition4 is not null then 1 else 0 end) as tagged
sum(case when condition1 is null or condition2 is null or condition3 is null or condition4 is null then 1 else 0 end) as untagged
from table
GROUP BY CASE
WHEN classification ='A' THEN 'X'
WHEN classification ='B' THEN 'Y'
WHEN classification ='C' THEN 'X'
WHEN classification ='D' THEN 'Z'
WHEN classification ='E' THEN 'Z'
WHEN classification ='F' THEN 'Y'
WHEN classification ='G' THEN 'X'
END ;