I have the following code
SELECT
dbo.tbl1.RecId, dbo.tbl1.CertType,
COUNT(dbo.tbl2.CertType) AS Quantity
FROM
dbo.tbl3
INNER JOIN
dbo.tbl2 ON dbo.tbl3.RequestNo = dbo.tbl2.RequestNo
RIGHT OUTER JOIN
dbo.tbl1 ON dbo.tbl2.CertType = dbo.tbl1.RecId
GROUP BY
dbo.tbl1.RecId, dbo.tbl1.CertType
And it returns this result:
RecId CertType Quantity
1 Clearance 4
2 Permit 0
It only counts the quantity from tbl3
but I want it to count also the records from tbl4
but just don't know how to add code for it.
Note: tbl4
has the same format with tlb3
. thanks for your help.
I want the result just like this:
RecId CertType Quantity
1 Clearance 4
2 Permit 2
In this case the over clause would be useful. There is an example in the appropriate section in the MSDN page that uses the count command. Your case should become something like:
SELECT
t.RecId, t.CertType,
COUNT(t.CertType) over (partition by t.RecId) AS Quantity
FROM
(SELECT dbo.tbl1.RecId, dbo.tbl1.CertType
FROM
dbo.tbl3
INNER JOIN dbo.tbl2 ON dbo.tbl3.RequestNo = dbo.tbl2.RequestNo
RIGHT OUTER JOIN dbo.tbl1 ON dbo.tbl2.CertType = dbo.tblBasicPermitFeeSchedule.RecId
UNION
SELECT dbo.tbl1.RecId, dbo.tbl1.CertType
FROM
dbo.tbl4
INNER JOIN dbo.tbl2 ON dbo.tbl4.RequestNo = dbo.tblRequests.RequestNo
RIGHT OUTER JOIN dbo.tbl1 ON dbo.tbl2.CertType = dbo.tbl1.RecId) t
GROUP BY
t.RecId, t.CertType
or something similar. I haven't tested it yet though, so it could be a bit different.
Let me know if something is unclear.
I think i got this solution that works for me.
SELECT dbo.tbl1.RecId, dbo.tbl1.CertType,
COUNT(dbo.tbl2.RequestNo) AS Quantity
FROM dbo.tbl3 INNER JOIN
dbo.tbl2 ON dbo.tbl3.RequestNo = dbo.tbl2.RequestNo
RIGHT OUTER JOIN
dbo.tbl1 ON dbo.tbl2.CertType = dbo.tblBasicPermitFeeSchedule.RecId
GROUP BY dbo.tbl1.RecId, dbo.tbl1.CertType
UNION
SELECT dbo.tbl1.RecId, dbo.tbl1.CertType,
COUNT(dbo.tbl2.RequestNo) AS Quantity
FROM dbo.tbl4 INNER JOIN
dbo.tbl2 ON dbo.tbl4.RequestNo = dbo.tblRequests.RequestNo
RIGHT OUTER JOIN
dbo.tbl1 ON dbo.tbl2.CertType = dbo.tbl1.RecId
GROUP BY dbo.tbl1.RecId, dbo.tbl1.CertType
Thanks for all your ideas.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.