计数,拥有和案例陈述
Posted
技术标签:
【中文标题】计数,拥有和案例陈述【英文标题】:Count, Having and Case statement 【发布时间】:2013-09-25 16:49:17 【问题描述】:我希望根据 3 个不同的条件(DB2 数据库)生成项目计数。我需要计算所有项目 = .5 和 >= 1.00 (percentage_used),但只能按 dim_building_id 和 building_name 分组。当然,这个查询不会运行,因为它需要将 percent_used 添加到 group by。如何使用 percent_used 处理这 3 个条件?
SELECT
SUM(CAST(FTS.GROUP_A AS BIGINT)) AS GROUP_A,
SUM(CAST(FTS.GROUP_B AS BIGINT)) AS GROUP_B,
SUM(CAST(FTS.GROUP_C AS BIGINT)) AS GROUP_C,
CASE WHEN FAT.PERCENTAGE_USED <= '0.10'
THEN COUNT(*)
END AS PROJECTS_L10,
CASE WHEN FAT.PERCENTAGE_USED >= '0.50'
THEN COUNT(*)
END AS PROJECTS_G50,
CASE WHEN FAT.PERCENTAGE_USED >= '1.00'
THEN COUNT(*)
END AS PROJECTS_G100,
DAYS(DATE('2014-07-01')) - DAYS(CURRENT DATE) AS DAYS_LEFT,
(DAYS(DATE('2014-07-01')) - DAYS(CURRENT DATE))/7 AS WEEKS_LEFT,
DAYS(DATE('2013-12-31')) - DAYS(CURRENT DATE) AS DAYS_LEFT_YEAR
FROM FACT_TABLE AS FAT
INNER JOIN GROUPS AS FTS ON FAT.DIM_PROJECT_ID = FTS.DIM_PROJECT_ID
GROUP BY FAT.DIM_BUILDING_ID, FAT.BUILDING_NAME;
【问题讨论】:
【参考方案1】:我会这样做:
select bn.building_name ,
t.*
from ( select fat.building_id ,
sum( case when fat.percentage_used <= 0.10 then 1 else 0 end ) as group_a ,
sum( case when fat.percentage_used > 0.10 and fat.percentage_used < 0.50 then 1 else 0 end ) as group_b ,
sum( case when fat.percentage_used >= 0.50 and fat.percentage_used < 1.00 then 1 else 0 end ) as group_c ,
sum( case when fat.percentage_used >= 1.00 then 1 else 0 end ) as group_d ,
sum( case when fat.percentage_used is null then 1 else 0 end ) as group_e
from fact_table fat
join groups fts on tfs.dim_project_id = fat.dim_project_id
group by fat.building_id
) t
join fact_table bn on bn.building_id = t.building_id
【讨论】:
添加范围的想法不错,但根据问题中的值,没有迹象表明需要范围。【参考方案2】:不要将聚合作为THEN
,而是将CASE
语句包装在聚合中:
SELECT
SUM(CAST(FTS.GROUP_A AS BIGINT)) AS GROUP_A,
SUM(CAST(FTS.GROUP_B AS BIGINT)) AS GROUP_B,
SUM(CAST(FTS.GROUP_C AS BIGINT)) AS GROUP_C,
SUM(CASE WHEN FAT.PERCENTAGE_USED <= '0.10' THEN 1 ELSE 0 END) AS PROJECTS_L10,
SUM(CASE WHEN FAT.PERCENTAGE_USED >= '0.50' THEN 1 ELSE 0 END) AS PROJECTS_G50,
SUM(CASE WHEN FAT.PERCENTAGE_USED >= '1.00' THEN 1 ELSE 0 END) AS PROJECTS_G100,
DAYS(DATE('2014-07-01')) - DAYS(CURRENT DATE) AS DAYS_LEFT,
(DAYS(DATE('2014-07-01')) - DAYS(CURRENT DATE))/7 AS WEEKS_LEFT,
DAYS(DATE('2013-12-31')) - DAYS(CURRENT DATE) AS DAYS_LEFT_YEAR
FROM FACT_TABLE AS FAT
INNER JOIN GROUPS AS FTS ON FAT.DIM_PROJECT_ID = FTS.DIM_PROJECT_ID
GROUP BY FAT.DIM_BUILDING_ID, FAT.BUILDING_NAME;
ELSE 0
不是必需的,但有些人喜欢在查询中看到它。
或者,这也应该有效:
COUNT(CASE WHEN FAT.PERCENTAGE_USED >= '0.50' THEN 1 END) AS PROJECTS_G50,
【讨论】:
实际上,您选择了最后一个,但很乐意提供帮助。以上是关于计数,拥有和案例陈述的主要内容,如果未能解决你的问题,请参考以下文章