我的查询需要帮助。我试图将具有不同WHERE条件的列的SUM除以例如
SELECT
TO_CHAR(PS.REPORT_PERIOD_END_DATE, 'YYYY') AS YR,
SUM(T1.PRICE) AS COLUMN_1
FROM TABLE_ONE T1
INNER JOIN SUB_STATUSES status ON status.SUB_ID = T1.ID
WHERE status.R_SUB_STATUS_CODE = 'COMPLETED'
AND T1.TYPE = 'COMPANY' OR T1.TYPE = 'SMALL_BUSINESS'
GROUP BY TO_CHAR(PS.REPORT_PERIOD_END_DATE, 'YYYY')
ORDER BY TO_CHAR(PS.REPORT_PERIOD_END_DATE, 'YYYY') DESC
DIVIDE BY
SELECT
TO_CHAR(PS.REPORT_PERIOD_END_DATE, 'YYYY') AS YR,
SUM(T1.PRICE) AS COLUMN_1
from TABLE_ONE T1
INNER JOIN SUB_STATUSES status ON status.SUB_ID = T1.ID
WHERE status.R_SUB_STATUS_CODE = 'COMPLETED'
AND T1.TYPE = 'LOT' OR T1.TYPE = 'LAND'
GROUP BY TO_CHAR(PS.REPORT_PERIOD_END_DATE, 'YYYY')
ORDER BY TO_CHAR(PS.REPORT_PERIOD_END_DATE, 'YYYY') DESC
第一列返回:
2017 1094
2016 89
2015 95
2014 101
2013 113
2012 173
2011 191
2010 165
答案 0 :(得分:1)
使用case语句而不是where子句。外部查询检查除以零。
SELECT yr, case when column_2 <> 0 then column_1/column2 else 0 end divcol
FROM (
SELECT
TO_CHAR(PS.REPORT_PERIOD_END_DATE, 'YYYY') AS YR,
SUM(case when t1.type in ('COMPANY', 'SMALL_BUSINESS') THEN T1.PRICE ELSE 0 END) as COLUMN_1,
SUM(case when t1.type in ('LOT', 'LAND') THEN T1.PRICE ELSE 0 end) AS COLUMN_2
FROM TABLE_ONE T1
INNER JOIN SUB_STATUSES status ON status.SUB_ID = T1.ID
WHERE status.R_SUB_STATUS_CODE = 'COMPLETED'
GROUP BY TO_CHAR(PS.REPORT_PERIOD_END_DATE, 'YYYY')
)
ORDER BY yr DESC