I have 1 table containing ticket information, and a second with knowledge article information. The tickets can be linked to the appropriate knowledge article.
In the ticket table (IncidentsM1) is a column CBA_KPF_ID which will either contain an article ID or a NULL.
I need to find out how many times each article was linked even if it's 0.
Tables (redacted):
- INCIDENTSM1 - Ticket table
- INCIDENT_ID - Ticket ID
- CBA_KPF_ID - Article ID
- KMDOCUMENTM1 - Article table
- ID - Article ID
If I use the following code, I get the number of links except for those with 0 links:
SELECT KM1.ID, COUNT(*) AS "Count"
FROM INCIDENTSM1 AS SD LEFT JOIN KMDOCUMENTM1 AS KM1 ON SD.CBA_KPF_ID=KM1.ID
GROUP BY KM1.ID
One of the results is an ID value of NULL with the count of tickets which haven't linked to an article.
If I use the following (from other question) code, I get a list of articles with the count either being 1 or 0 and article IDs appearing in multiple rows:
SELECT SD.CBA_KPF_ID, ISNULL(KM."Count", 0) FROM
(SELECT CBA_KPF_ID FROM INCIDENTSM1) SD
LEFT JOIN
(SELECT ID, count(ID) as "Count" FROM KMDOCUMENTM1 GROUP BY ID) KM
ON SD.CBA_KPF_ID=KM.ID
ORDER BY "Count" DESC
Is it possible to get the list of articles and how many times they were linked even if the number is 0?
EDIT:
I've tried both below answers, but they're either failing to group by ID or still not showing 0 values.
I just tried to generate the list without 0 values, then union a table with all the IDs not in the first statement:
(SELECT KM1.ID, COUNT(*) AS "Count"
FROM INCIDENTSM1 AS SD LEFT JOIN KMDOCUMENTM1 AS KM1 ON SD.CBA_KPF_ID=KM1.ID
GROUP BY KM1.ID)
UNION
SELECT KM.ID, 0
FROM KMDOCUMENTM1 AS KM
WHERE KM.ID NOT IN (
SELECT A.ID FROM
(SELECT KM1.ID, COUNT(*) AS "Count"
FROM INCIDENTSM1 AS SD LEFT JOIN KMDOCUMENTM1 AS KM1 ON SD.CBA_KPF_ID=KM1.ID GROUP BY KM1.ID) A
)
ORDER BY "Count" DESC
Problem here is everything below the UNION seems not to return anything.