我正在运行两个SQL查询,每个查询返回一个包含3行的表,我需要执行一个数学运算符以减去两个表中的每一行
这是第一个查询,它向我返回3个具有x值的行,例如
SELECT COUNT (*) AS MES
FROM WorkOrder
WHERE asset LIKE '%DC1%'
AND YEAR (workOrderDate) BETWEEN 2018/11/01 AND 2018/11/31
OR businessUnit ='MM'
OR workType = '07'
OR workType = '08'
OR workType = '09'
OR workType = '10'
OR workType = '01'
UNION ALL
SELECT COUNT (*) AS MES
FROM WorkOrder
WHERE asset LIKE '%DC2%'
AND YEAR (workOrderDate) BETWEEN 2018/11/01 AND 2018/11/31
OR businessUnit ='MM'
OR workType = '07'
OR workType = '08'
OR workType = '09'
OR workType = '10'
OR workType = '01'
UNION ALL
SELECT COUNT (*) AS MES
FROM WorkOrder
WHERE asset NOT LIKE '%DC1%' AND asset NOT LIKE '%DC2%'
AND YEAR (workOrderDate) BETWEEN 2018/11/01 AND 2018/11/31
OR businessUnit ='MM'
OR workType = '07'
OR workType = '08'
OR workType = '09'
OR workType = '10'
OR workType = '01
这是第二个查询,它向我返回具有其他值的相同内容
SELECT COUNT(*) AS MES
FROM WorkOrder
WHERE asset LIKE '%DC1%'
AND YEAR(workOrderDate) BETWEEN 2018/11/01 AND 2018/11/31
OR businessUnit ='MM'
OR workType = '07'
OR workType = '08'
OR workType = '09'
OR workType = '10'
OR workType = '01'
AND businessUnit ='MM'
UNION ALL
SELECT COUNT(*) AS MES
FROM WorkOrder
WHERE asset LIKE '%DC2%'
AND YEAR(workOrderDate) BETWEEN 2018/11/01 AND 2018/11/31
OR businessUnit ='MM'
OR workType = '07'
OR workType = '08'
OR workType = '09'
OR workType = '10'
OR workType = '01'
AND businessUnit ='MM'
UNION ALL
SELECT COUNT(*) AS MES
FROM WorkOrder
WHERE asset NOT LIKE '%DC1%' AND asset NOT LIKE '%DC2%'
AND YEAR(workOrderDate) BETWEEN 2018/11/01 AND 2018/11/31
OR businessUnit ='MM'
OR workType = '07'
OR workType = '08'
OR workType = '09'
OR workType = '10'
OR workType = '01'
AND businessUnit ='MM'
我需要执行一项从每个查询中减去值的操作,例如
SQL中是否有一种方法可以做到这一点?我只能在同一张表中找到运算符,无法弄清楚该如何执行。
答案 0 :(得分:1)
像这样向每个表提供一个行号。
select t1.*, t2.b, t1.mes - t2.mes from
(select *,row_number() over (order by mes) a from table1)t1 join
(select *,row_number() over (order by mes) b from table2)t2 on t1.a = t2.b