我正在尝试将对Authoriser的两个查询的结果合并到一个网格的结果集中。
SQL查询:
SELECT DISTINCT
Authoriser, ISNULL(TotalInvoices,0) AS TotalInvoices,
ISNULL(TotalRequsitions, 0) AS TotalRequsitions
FROM
(SELECT
Authoriser AS Authoriser,
COUNT(Tiffindex.Page_No) AS TotalInvoices,
null AS TotalRequsitions
FROM
Tiffindex
WHERE
Tiffindex.Doc_status = 7
AND authoriser != ''
GROUP BY
Authoriser
UNION
SELECT
Authoriser, null,
COUNT(RequisitionDetails.UploadTransaction_Id) AS TotalRequsitions
FROM
RequisitionDetails
WHERE
RequisitionDetails.Doc_status = 7 AND authoriser != ''
GROUP BY
Authoriser) AS secondset
是否可以更改SQL以将结果合并到1个Authoriser行中?
我得到的结果每个授权者可以产生2行。如果可能的话,我希望1?
预先感谢, 格雷厄姆
答案 0 :(得分:1)
您可以尝试以下-
SELECT Authoriser, sum(ISNULL(TotalInvoices,0)) AS TotalInvoices, sum(ISNULL(TotalRequsitions,0)) AS TotalRequsitions FROM (
select Authoriser As Authoriser, Count(Tiffindex.Page_No) as TotalInvoices, null as TotalRequsitions
from Tiffindex
where Tiffindex.Doc_status = 7 and authoriser != ''
group by Authoriser
UNION
select Authoriser, null, Count(RequisitionDetails.UploadTransaction_Id) as TotalRequsitions
from RequisitionDetails
where RequisitionDetails.Doc_status = 7 and authoriser != ''
group by Authoriser
) as secondset group by Authoriser
答案 1 :(得分:1)
我建议在外部查询中按授权者进行汇总,然后取其他两列的总和:
SELECT
Authoriser,
SUM(TotalInvoices) AS TotalInvoices,
SUM(TotalRequsitions) AS TotalRequsitions
FROM
(
SELECT
Authoriser As Authoriser,
COUNT(Page_No) AS TotalInvoices,
NULL AS TotalRequsitions
FROM Tiffindex
WHERE Doc_status = 7 AND authoriser != ''
GROUP BY Authoriser
UNION ALL
SELECT
Authoriser,
NULL,
COUNT(UploadTransaction_Id) AS TotalRequsitions
FROM RequisitionDetails
WHERE Doc_status = 7 AND Authoriser != ''
GROUP BY Authoriser
) AS secondset
GROUP BY
Authoriser;