嵌套查询并将其结果作为别名传递给SUM

时间:2019-02-08 17:10:23

标签: sql sql-server

因此,我正在运行两个查询,这些查询返回一年中每月每月X个项目的数量。

第一个查询给我以下结果

1st query

“无列名”将是月份,因此我没有8月,11月和12月的数据。

第二个查询,给出以下内容

2nd query

只有August和Setpember有数据。

我要弄清楚的是如何对两个表求和以得到100%的值,然后定义每个%(corretivas x preventivas)。 在我的研究中,我假设我必须嵌套查询,但是我无法达到使我接近所需结果的逻辑。

这是我到目前为止的查询

select month(workOrderDate), COUNT(*) as preventivas from WorkOrder WHERE
workOrderDescription = 'preventiva'
AND YEAR(workOrderDate) = 2018
AND lastUpdateData IS NOT NULL
AND WorkType = '02'
group BY MONTH(workOrderDate)
ORDER BY MONTH(workOrderDate)

select MONTH(workOrderDate), COUNT(*) AS corretivas from WorkOrder WHERE
YEAR(workOrderDate) = 2018
AND workOrderDescription = 'CORRETIVA' 
AND lastUpdateData IS NOT NULL
GROUP BY MONTH(workOrderDate)
ORDER BY MONTH(workOrderDate)

预期结果将是

expected result 等等

有人可以帮我吗?

1 个答案:

答案 0 :(得分:1)

您需要条件聚合:

SELECT MONTH(wo.workOrderDate), COUNT(*) AS total,
       (SUM(CASE WHEN wo.WorkType = '02' AND wo.orkOrderDescription = 'preventiva' THEN 1 ELSE 0 END) * 1.0 / COUNT(*)) * 100 AS preventiva,
       (SUM(CASE WHEN wo.orkOrderDescription = 'CORRETIVA' THEN 1 ELSE 0 END) * 1.0 / COUNT(*)) * 100 AS CORRETIVA
FROM WorkOrder wo
WHERE YEAR(wo.workOrderDate) = 2018 AND wo.lastUpdateData IS NOT NULL
GROUP BY MONTH(wo.workOrderDate);