以下是我的查询。我正在使用UNION ALL,因为当MONTH列既不是NULL又是NULL时,我需要带数据。 但这不起作用,我想知道为什么。
SELECT metricname,
careertrackid,
monthyrname,
SUM(metricvalue) AS metricval,
CASE
WHEN MONTH IS NOT NULL THEN CONVERT(VARCHAR,YEAR) + LPAD(CONVERT(VARCHAR,MONTH),2,'0')
ELSE CONVERT(VARCHAR,acnfiscalyear) + CONVERT(VARCHAR,acnfiscalquarter)
END AS dispmonth
FROM atp_9375_forecast,
vspforecasts
WHERE ibfcollectionid = vspforecasts.ibfid
AND (YEAR>= 2018 AND MONTH>= 7)
GROUP BY careertrackid,
metricname,
dispmonth,
monthyrname
ORDER BY dispmonth
UNION ALL
SELECT metricname,
careertrackid,
monthyrname,
SUM(metricvalue) AS metricval,
CASE
WHEN MONTH IS NOT NULL THEN CONVERT(VARCHAR,YEAR) + LPAD(CONVERT(VARCHAR,MONTH),2,'0')
ELSE CONVERT(VARCHAR,acnfiscalyear) + CONVERT(VARCHAR,acnfiscalquarter)
END AS dispmonth
FROM atp_9375_forecast,
vspforecasts
WHERE ibfcollectionid = vspforecasts.ibfid
AND (YEAR>= 2018 AND MONTH IS NULL)
GROUP BY careertrackid,
metricname,
dispmonth,
monthyrname
ORDER BY dispmonth
还有没有其他方法可以应用MONTH过滤器,但是应该同时包含NULL和NOT NULL,因为MONTH列在表中同时具有这两个值。
采样结果 这是理想的结果,但这仅在MONTH列包含NULL和NOT NULL时出现
{"201806":"0.00","201807":"0.00","201808":"0.00","201809":"0.00","201810":"0.00","201811":"0.00","FY19Q2":"0.00","FY19Q3":"0.00","FY19Q4":"0.00","FY20Q1":"0.00"}
答案 0 :(得分:2)
根据您的问题,您的union all
两个查询几乎相同,仅需month
来判断,您无需使用UNION ALL
,只需使用添加条件{{1 }}在(MONTH>= 7 OR MONTH IS NULL)
WHERE
注意
我建议避免使用SELECT metricname,
careertrackid,
monthyrname,
SUM(metricvalue) AS metricval,
CASE
WHEN MONTH IS NOT NULL THEN CONVERT(VARCHAR,YEAR) + LPAD(CONVERT(VARCHAR,MONTH),2,'0')
ELSE CONVERT(VARCHAR,acnfiscalyear) + CONVERT(VARCHAR,acnfiscalquarter)
END AS dispmonth
FROM atp_9375_forecast INNER JOIN
vspforecasts ON ibfcollectionid = vspforecasts.ibfid
WHERE (YEAR>= 2018 AND (MONTH>= 7 OR MONTH IS NULL))
GROUP BY careertrackid,
metricname,
dispmonth,
monthyrname
ORDER BY dispmonth
逗号连接表,因为它是一种旧样式,可以使用,
代替它。