patternsqlModerate
Count instances of value in multiple tables
Viewed 0 times
tablesinstancesvaluemultiplecount
Problem
I'm attempting to write a query that returns the count of a given value across multiple tables.
Right now, I'm using the following query
Which returns a single result with the count of lines in Sales Line in the first column and the count from Sales Line Archive in the second.
However, I'd like to request multiple records using an
Right now, I'm using the following query
SELECT COUNT(*) AS SL,
(
SELECT COUNT(*)
FROM [Sales Line Archive]
WHERE [Document No_] = 123
) AS SLA
FROM [Sales Line]
WHERE [Document No_] = 123Which returns a single result with the count of lines in Sales Line in the first column and the count from Sales Line Archive in the second.
However, I'd like to request multiple records using an
IN clause, so that I could get results like the followingDocument No_, SL, SLA
1, 3, 0
2, 0, 4
3, 2, 1Solution
One way would be to pivot
I'd hope that the predicate on
WITH CTE AS
(
SELECT [Document No_], 'SL' AS Source
FROM [Sales Line]
UNION ALL
SELECT [Document No_], 'SLA' AS Source
FROM [Sales Line Archive]
)
SELECT P.[Document No_],
P.SL,
P.SLA
FROM CTE
PIVOT (COUNT(Source) FOR Source IN ([SL], [SLA])) P
WHERE P.[Document No_] IN (1,2,3);I'd hope that the predicate on
[Document No_] gets pushed up into the selects from the source tables. Check the execution plans to be sure.Code Snippets
WITH CTE AS
(
SELECT [Document No_], 'SL' AS Source
FROM [Sales Line]
UNION ALL
SELECT [Document No_], 'SLA' AS Source
FROM [Sales Line Archive]
)
SELECT P.[Document No_],
P.SL,
P.SLA
FROM CTE
PIVOT (COUNT(Source) FOR Source IN ([SL], [SLA])) P
WHERE P.[Document No_] IN (1,2,3);Context
StackExchange Database Administrators Q#139653, answer score: 10
Revisions (0)
No revisions yet.