我正在使用SQL Server 2005.
我怎么能重构这个查询?
SELECT Total, Installs, Service, tot.ls_chg_dte_ojb
FROM (SELECT COUNT(*) [Total], ls_chg_dte_ojb
FROM [COMPL_INST_SVC]
GROUP BY ls_chg_dte_ojb) tot
JOIN (SELECT COUNT(*) [Service], ls_chg_dte_ojb
FROM [COMPL_INST_SVC]
WHERE job_class_ojb = 'S'
GROUP BY ls_chg_dte_ojb) svc on svc.ls_chg_dte_ojb = tot.ls_chg_dte_ojb
JOIN (SELECT COUNT(*) [Installs], ls_chg_dte_ojb
FROM [COMPL_INST_SVC]
WHERE job_class_ojb in ('C', 'R')
GROUP BY ls_chg_dte_ojb) ins on ins.ls_chg_dte_ojb = tot.ls_chg_dte_ojb
答案 0 :(得分:2)
您的两个子选项是相同的。忽略“服务”,尝试按照
的方式SELECT
SUM(CASE WHEN job_class_ojb = 'S' THEN 1 ELSE 0 END) as Total,
SUM(CASE WHEN job_class_ojb = 'C' or
job_class_ojb = 'R' THEN 1 ELSE 0 END) as Installs
FROM COMPL_INST_SVC
答案 1 :(得分:2)
看起来总计和服务计数都是相同的,所以你需要解决这个问题,但这里基本上是你如何以更简单的方式进行计数:
SELECT
COUNT(CASE WHEN job_class_ojb = 'S' THEN 1 END) AS [Total],
COUNT(CASE WHEN job_class_ojb = 'S' THEN 1 END) AS [Service],
COUNT(CASE WHEN job_class_ojb in ('C', 'R') THEN 1 END) AS [Installs]
FROM
[COMPL_INST_SVC]
答案 2 :(得分:1)
我怀疑Totals子查询不应包含WHERE job_class_ojb = 'S'
条件 - 如果是这样,我建议:
SELECT COUNT(*) Total,
SUM(CASE WHEN job_class_ojb = 'S' THEN 1 ELSE 0 END) Service,
SUM(CASE WHEN job_class_ojb in ('C','R') THEN 1 ELSE 0 END) Installs,
ls_chg_dte_ojb
FROM COMPL_INST_SVC
GROUP BY ls_chg_dte_ojb