我陷入了条件雪花选择sql。当它们具有相应的分类值时,我正在尝试计算ID。我将不胜感激。
谢谢
SELECT
YEAR(DATETIME) AS YEAR,
WEEKOVERYEAR(DATETIME) AS WEEK,
COUNT(CASE WHEN ID THEN CATEGORY = 'A')
from table
group by week, year;
答案 0 :(得分:1)
这是一种方法:
SELECT YEAR(DATETIME) AS YEAR,
WEEKOVERYEAR(DATETIME) AS WEEK,
SUM(CASE WHEN CATEGORY = 'A' THEN 1 ELSE 0 END) as num_a
FROM table
GROUP BY week, year;
答案 1 :(得分:1)
雪花支持COUNT_IF:
返回满足条件的记录数。
汇总功能
COUNT_IF( <condition> )
SELECT YEAR(DATETIME) AS YEAR,
WEEKOVERYEAR(DATETIME) AS WEEK,
COUNT_IF(CATEGORY = 'A') AS num_a
FROM tab
GROUP BY week, year;
答案 2 :(得分:0)
COUNT()计算不为空的行数。 如果要在ID不为空且CATEGORY ='A'时使用
COUNT(CASE WHEN ID IS NOT NULL AND CATEGORY = 'A' THEN TRUE ELSE NULL END)
将为您提供,或者您可以使用戈登答案中的SUM
SUM(CASE WHEN ID IS NOT NULL AND CATEGORY = 'A' THEN 1 ELSE 0 END)
或者您可以将雪花IFF用作同一件事的缩写,这就是我的做法
SUM( IFF( ID IS NOT NULL AND CATEGORY = 'A', 1, 0))
答案 3 :(得分:0)
你应该/可以使用 IFF() 因为 case when 在有多个条件时更合适。
SELECT
YEAR(DATETIME) AS YEAR,
WEEKOVERYEAR(DATETIME) AS WEEK,
COUNT(IFF(CATEGORY = 'A',ID,NULL)) as count
from table
group by week, year;