我已经生成了以下查询,并且我想通过我在查询中创建的新IMS_CUST_ID_GRP(将其汇总到此处,删除CUST_ID)来计算患者计数。如何修改我的查询以返回我想要的结果?我尝试使用分析函数,但是我收到了错误。
SELECT (CASE WHEN SUM(NEW_PAT_CNT) = 1 THEN '1'
WHEN SUM(NEW_PAT_CNT) >=2 AND SUM(NEW_PAT_CNT) <=12 THEN '2-12'
WHEN SUM(NEW_PAT_CNT) >=13 AND SUM(NEW_PAT_CNT)<=24 THEN '13-24'
WHEN SUM(NEW_PAT_CNT) >=24 AND SUM(NEW_PAT_CNT) <=48 THEN '25-48'
WHEN SUM(NEW_PAT_CNT) >48 THEN '>48'
END) IMS_CUST_ID_GRP, SUM(NEW_PAT_CNT), CUST_ID
FROM DEXODS.OPUB_ONE_IMS_IDS_FACT fct,
DEXWHS.D_DATE dt,
DEXWHS.D_ACCOUNT_VEEVA ac
WHERE fct.DATE_DIM_KEY = dt.DATE_ID
AND fct.ACCOUNT_DIM_KEY = ac.ACCOUNT_DIM_KEY
AND NEW_PAT_CNT >0
AND dt.year in n'2016'
GROUP BY CUST_ID
返回错误的分析函数
SELECT (CASE WHEN SUM(NEW_PAT_CNT) OVER (PARTITION BY CUST_ID) = 1 THEN '1'
WHEN SUM(NEW_PAT_CNT) OVER (PARTITION BY CUST_ID) >=2 AND SUM(NEW_PAT_CNT)OVER (PARTITION BY CUST_ID) <=12 THEN '2-12'
WHEN SUM(NEW_PAT_CNT) OVER (PARTITION BY CUST_ID) >=13 AND SUM(NEW_PAT_CNT)OVER (PARTITION BY CUST_ID) <=24 THEN '13-24'
WHEN SUM(NEW_PAT_CNT) OVER (PARTITION BY CUST_ID) >=24 AND SUM(NEW_PAT_CNT)OVER (PARTITION BY CUST_ID) <=48 THEN '25-48'
WHEN SUM(NEW_PAT_CNT) OVER (PARTITION BY CUST_ID) >48 THEN '>48'
END) IMS_CUST_ID_GRP, CUST_ID, SUM(NEW_PAT_CNT)
FROM DEXODS.OPUB_ONE_IMS_IDS_FACT fct,
DEXWHS.D_DATE dt,
DEXWHS.D_ACCOUNT_VEEVA ac
WHERE fct.DATE_DIM_KEY = dt.DATE_ID
AND fct.ACCOUNT_DIM_KEY = ac.ACCOUNT_DIM_KEY
AND NEW_PAT_CNT >0
GROUP BY CUST_ID
Dataset with CUST_ID included
IMS_CUST_ID_GRP SUM(NEW_PAT_CNT) CUST_ID
1 1 55671832
1 1 56097728
2-12 4 56106239
2-12 5 56728330
2-12 9 57590869
2-12 2 55609391
2-12 9 55880657
2-12 10 56339375
2-12 3 57371546
25-48 39 55891493
13-24 21 55714333
13-24 22 56542678
Desired Dataset rolled up to IMS_CUST_ID_GRP
IMS_CUST_ID_GRP SUM(NEW_PAT_CNT)
1 2
2-12 42
13-24 43
25-48 39
答案 0 :(得分:0)
如果您正在使用GROUP BY
进行数据透视查询,则无需使用SUM()
作为分析函数。只需正常使用它:
SELECT CUST_ID,
SUM(CASE WHEN CUST_ID = 1 THEN NEW_PAT_CNT ELSE 0 END) AS '1',
SUM(CASE WHEN CUST_ID >= 2 AND CUST_ID <= 12 THEN NEW_PAT_CNT ELSE 0 END) AS '2-12',
SUM(CASE WHEN CUST_ID >= 13 AND CUST_ID <= 24 THEN NEW_PAT_CNT ELSE 0 END) AS '13-24',
SUM(CASE WHEN CUST_ID >= 24 AND CUST_ID <= 48 THEN NEW_PAT_CNT ELSE 0 END) AS '25-48',
SUM(CASE WHEN CUST_ID > 48 THEN NEW_PAT_CNT ELSE 0 END) AS '>48'
FROM DEXODS.OPUB_ONE_IMS_IDS_FACT fct
INNER JOIN DEXWHS.D_DATE dt
ON fct.DATE_DIM_KEY = dt.DATE_ID
INNER JOIN DEXWHS.D_ACCOUNT_VEEVA ac
ON fct.ACCOUNT_DIM_KEY = ac.ACCOUNT_DIM_KEY
WHERE NEW_PAT_CNT > 0 -- should not be necessary assuming count no less than zero
GROUP BY CUST_ID
请注意,我已使用显式INNER JOIN
替换了您的隐式连接。您可能已经听过,应该尽量避免在逗号FROM
中添加逗号。