这是我的查询运行查找总计。
我只是在这里混淆。请告诉我。
SELECT
CASE
WHEN SUBSTRING(FL.TRAN,1,2)='02' THEN 'TOTAL APPLES:'
WHEN SUBSTRING(FL.TRAN,1,2)='01' THEN 'TOTAL BANANAS:'
WHEN SUBSTRING(FL.TRAN,1,2)='40' THEN 'TOTAL ORANGES:'
WHEN SUBSTRING(FL.TRAN,1,2)='31' THEN 'TOTAL GRAPES:'
END TYPE,
COUNT(FR.AMT) COUNT,
ISNULL(SUM(FR.AMT),0) AMOUNT
FROM
MYDB.FIN_FRUITLIST201706 AS FL
JOIN
MYDB.FIN_FRUITRATE201706 AS FR ON FL.TSTAMP_TRANS = FR.TSTAMP_TRANS
AND FL.UNIQUENESS_KEY = FR.UNIQUENESS_KEY
WHERE
FL.TSTAMP_TRANS LIKE'201706%'
AND SUBSTRING(FL.TRAN, 1, 2) IN ('02', '01', '40', '31')
GROUP BY
CASE
WHEN SUBSTRING(FL.TRAN,1,2)='02' THEN 'TOTAL APPLES:'
WHEN SUBSTRING(FL.TRAN,1,2)='01' THEN 'TOTAL BANANAS:'
WHEN SUBSTRING(FL.TRAN,1,2)='40' THEN 'TOTAL ORANGES:'
WHEN SUBSTRING(FL.TRAN,1,2)='31' THEN 'TOTAL GRAPES:'
END
UNION ALL
SELECT
'GRAND TOTALS:' TYPE,
COUNT(FR.AMT) COUNT,
ISNULL(SUM(FR.AMT),0) AMOUNT
FROM
MYDB.FIN_FRUITLIST201706 AS FL
JOIN
MYDB.FIN_FRUITRATE201706 AS FR ON FL.TSTAMP_TRANS = FR.TSTAMP_TRANS
AND FL.UNIQUENESS_KEY = FR.UNIQUENESS_KEY
WHERE
FL.TSTAMP_TRANS LIKE'201706%'
AND SUBSTRING(FL.TRAN, 1, 2) IN ('02', '01', '40', '31');
以下是输出的屏幕截图:
如果总数没有任何值,只需要在此处显示为零。
如果表中没有苹果,只想放零。
我只是在这里混淆。请告诉我。
答案 0 :(得分:0)
请尝试此操作并检查结果。
SELECT
CASE
WHEN SUBSTRING(FL.TRAN,1,2)='02' THEN 'TOTAL APPLES:'
WHEN SUBSTRING(FL.TRAN,1,2)='01' THEN 'TOTAL BANANAS:'
WHEN SUBSTRING(FL.TRAN,1,2)='40' THEN 'TOTAL ORANGES:'
WHEN SUBSTRING(FL.TRAN,1,2)='31' THEN 'TOTAL GRAPES:'
END TYPE,
COUNT(FR.AMT) COUNT,
ISNULL(SUM(FR.AMT),0) AMOUNT
FROM
MYDB.FIN_FRUITLIST201706 AS FL
LEFT JOIN
MYDB.FIN_FRUITRATE201706 AS FR ON FL.TSTAMP_TRANS = FR.TSTAMP_TRANS
AND FL.UNIQUENESS_KEY = FR.UNIQUENESS_KEY
WHERE
FL.TSTAMP_TRANS LIKE'201706%'
AND SUBSTRING(FL.TRAN, 1, 2) IN ('02', '01', '40', '31')
GROUP BY
CASE
WHEN SUBSTRING(FL.TRAN,1,2)='02' THEN 'TOTAL APPLES:'
WHEN SUBSTRING(FL.TRAN,1,2)='01' THEN 'TOTAL BANANAS:'
WHEN SUBSTRING(FL.TRAN,1,2)='40' THEN 'TOTAL ORANGES:'
WHEN SUBSTRING(FL.TRAN,1,2)='31' THEN 'TOTAL GRAPES:'
END
UNION ALL
SELECT
'GRAND TOTALS:' TYPE,
COUNT(FR.AMT) COUNT,
ISNULL(SUM(FR.AMT),0) AMOUNT
FROM
MYDB.FIN_FRUITLIST201706 AS FL
JOIN
MYDB.FIN_FRUITRATE201706 AS FR ON FL.TSTAMP_TRANS = FR.TSTAMP_TRANS
AND FL.UNIQUENESS_KEY = FR.UNIQUENESS_KEY
WHERE
FL.TSTAMP_TRANS LIKE'201706%'
AND SUBSTRING(FL.TRAN, 1, 2) IN ('02', '01', '40', '31');