我有三个SELECT语句在多个结果集中返回:
SELECT COUNT(*) AS OrdersInStep1 FROM
(SELECT DISTINCT
os.db_OrderNo
FROM tblOrders os
JOIN tblRefOrderType ot on ot.db_OrderType = os.db_OrderType
LEFT JOIN tblDate d on d.db_SeqNo = os.db_Status
WHERE
os.db_Deleted = 0
AND db_Date39 = '1900/01/01'
AND d.db_Task = 1) AS OrdersInStep1
SELECT COUNT(*) AS OrdersInStep2 FROM
(SELECT DISTINCT
os.db_OrderNo
FROM tblOrders os
JOIN tblRefOrderType ot on ot.db_OrderType = os.db_OrderType
LEFT JOIN tblDate d on d.db_SeqNo = os.db_Status
WHERE
os.db_Deleted = 0
AND db_Date39 = '1900/01/01'
AND d.db_Task = 2) AS OrdersInStep2
SELECT COUNT(*) AS OrdersInStep3 FROM
(SELECT DISTINCT
os.db_OrderNo
FROM tblOrders os
JOIN tblRefOrderType ot on ot.db_OrderType = os.db_OrderType
LEFT JOIN tblDate d on d.db_SeqNo = os.db_Status
WHERE
os.db_Deleted = 0
AND db_Date39 = '1900/01/01'
AND (d.db_Task = 3 OR d.db_Task = 4)
AND d.db_SeqNo != 34
AND d.db_SeqNo != 31) AS OrdersInStep3
我可以使用UNION
将这些结果集合并到一个列中,但是如何将它们组合成一个结果集,但是三列呢?
示例:
OrdersInStep1 | OrdersInStep2 | OrdersInStep3
12 | 16 | 3
答案 0 :(得分:2)
您可以构建一个具有您需要的订单的CTE,这样您就不必继续运行相同的查询3次..然后只需从CTE中选择您的计数。临时表也可以在这里接受,而不是CTE,甚至可能表现稍好......
WITH cte AS (
SELECT
os.db_OrderNo,
d.db_SeqNo,
d.db_Task
FROM
tblOrders os
JOIN tblRefOrderType ot ON ot.db_OrderType = os.db_OrderType
JOIN tblDate d ON d.db_SeqNo = os.db_Status
WHERE
os.db_Deleted = 0
AND db_Date39 = '1900/01/01'
AND d.db_Task IN (1, 2, 3, 4)
)
SELECT
(SELECT COUNT(DISTINCT db_OrderNo)
FROM cte
WHERE db_Task = 1) OrdersInStep1,
(SELECT COUNT(DISTINCT db_OrderNo)
FROM cte
WHERE db_Task = 2) OrdersInStep2,
(SELECT COUNT(DISTINCT db_OrderNo)
FROM cte
WHERE db_Task IN (3, 4)
AND db_SeqNo NOT IN (31, 34)) OrdersInStep3
答案 1 :(得分:1)
你几乎就在那里,你只需要在每个select语句中都有匹配的列数。您可以根据需要传递空的''
或NULL
值。
SELECT COUNT(*) AS OrdersInStep1, NULL as OrdersInStep2, NULL as OrdersInStep3 FROM
(SELECT DISTINCT
os.db_OrderNo
FROM tblOrders os
JOIN tblRefOrderType ot on ot.db_OrderType = os.db_OrderType
LEFT JOIN tblDate d on d.db_SeqNo = os.db_Status
WHERE
os.db_Deleted = 0
AND db_Date39 = '1900/01/01'
AND d.db_Task = 1) AS OrdersInStep1
UNION
SELECT NULL as OrdersInStep1, COUNT(*) AS OrdersInStep2, NULL as OrdersInStep3 FROM
(SELECT DISTINCT
os.db_OrderNo
FROM tblOrders os
JOIN tblRefOrderType ot on ot.db_OrderType = os.db_OrderType
LEFT JOIN tblDate d on d.db_SeqNo = os.db_Status
WHERE
os.db_Deleted = 0
AND db_Date39 = '1900/01/01'
AND d.db_Task = 2) AS OrdersInStep2
UNION
SELECT NULL as OrdersInStep1, NULL as OrdersInStep2, COUNT(*) AS OrdersInStep3 FROM
(SELECT DISTINCT
os.db_OrderNo
FROM tblOrders os
JOIN tblRefOrderType ot on ot.db_OrderType = os.db_OrderType
LEFT JOIN tblDate d on d.db_SeqNo = os.db_Status
WHERE
os.db_Deleted = 0
AND db_Date39 = '1900/01/01'
AND (d.db_Task = 3 OR d.db_Task = 4)
AND d.db_SeqNo != 34
AND d.db_SeqNo != 31) AS OrdersInStep3