我有这样的查询:
SELECT COUNT(DISTINCT ACCOUNT_CODE), ZERO_DAYS_FLAG FROM (
SELECT SUM (CLASS_BELOW_BALANCE) AS ZERO_DAYS_FLAG, ACCOUNT_CODE
FROM ACCOUNT_BALANCES
WHERE MERCHANT_STATUS != 'Suspended'
AND MERCHANT_CSP_CODE IN ('1' , '2' , '3' , '4' , '5' , '6' , '7')
AND CHECK_BALANCE_DATE BETWEEN '01-SEP-15' AND '30-SEP-15'
GROUP BY ACCOUNT_CODE) GROUP BY ZERO_DAYS_FLAG ORDER BY ZERO_DAYS_FLAG;
,结果如下:
COUNT(DISTINCTACCOUNT_CODE) ZERO_DAYS_FLAG
--------------------------- ----------------------
2026 0
2036 1
2005 2
1874 3
2020 4
2074 5
2224 6
2343 7
2460 8
2666 9
2606 10
2511 11
2571 12
我需要的是在ZERO_DAYS_FLAG大于6时添加一个案例,然后将结果总计为6天,如下所示:
COUNT(DISTINCTACCOUNT_CODE) ZERO_DAYS_FLAG
--------------------------- ----------------------
2026 0
2036 1
2005 2
1874 3
2020 4
2074 5
2224 6+
答案 0 :(得分:2)
使用此CASE
表达式:
CASE WHEN ZERO_DAYS_FLAG > 5 THEN '+6' ELSE CAST(ZERO_DAYS_FLAG AS CHAR) END
像这样:
SELECT
COUNT(DISTINCT ACCOUNT_CODE),
CASE WHEN ZERO_DAYS_FLAG > 5 THEN '6+' ELSE CAST(ZERO_DAYS_FLAG AS CHAR) END ZERO_DAYS_FLAG
FROM (
SELECT SUM(CLASS_BELOW_BALANCE) AS ZERO_DAYS_FLAG, ACCOUNT_CODE
FROM ACCOUNT_BALANCES
WHERE MERCHANT_STATUS != 'Suspended'
AND MERCHANT_CSP_CODE IN ('1' , '2' , '3' , '4' , '5' , '6' , '7')
AND CHECK_BALANCE_DATE BETWEEN '01-SEP-15' AND '30-SEP-15'
GROUP BY ACCOUNT_CODE) X
GROUP BY CASE WHEN ZERO_DAYS_FLAG > 5 THEN '6+' ELSE CAST(ZERO_DAYS_FLAG AS CHAR) END
ORDER BY CASE WHEN ZERO_DAYS_FLAG > 5 THEN '6+' ELSE CAST(ZERO_DAYS_FLAG AS CHAR) END;
注意:值" 6 +"在原始查询中已更改为" + 6"如果结果也被应用程序使用,则允许它仍然被识别为整数。所有这一点都归功于OP。
答案 1 :(得分:0)
SELECT
COUNT(DISTINCT ACCOUNT_CODE),
CASE WHEN ZERO_DAYS_FLAG > 6 THEN '6+' ELSE ZERO_DAYS_FLAG || '' END AS zero_days_flag
FROM (
SELECT
SUM (CLASS_BELOW_BALANCE) AS ZERO_DAYS_FLAG, ACCOUNT_CODE
FROM ACCOUNT_BALANCES
WHERE MERCHANT_STATUS != 'Suspended'
AND MERCHANT_CSP_CODE IN ('1' , '2' , '3' , '4' , '5' , '6' , '7')
AND CHECK_BALANCE_DATE BETWEEN '01-SEP-15' AND '30-SEP-15'
GROUP BY ACCOUNT_CODE)
GROUP BY ZERO_DAYS_FLAG ORDER BY ZERO_DAYS_FLAG;