因此,我正在运行两个查询,这些查询返回一年中每月每月X个项目的数量。
第一个查询给我以下结果
“无列名”将是月份,因此我没有8月,11月和12月的数据。
第二个查询,给出以下内容
只有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)
预期结果将是
有人可以帮我吗?
答案 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);