Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Select with no records in derived count

Author  Topic 

John Sourcer
Yak Posting Veteran

91 Posts

Posted - 2007-09-28 : 04:35:20
Hi All,

I have the following query:

SELECT l.ID, l.LibraryName, SUM(o.total) as recs FROM
( SELECT p.LibraryID, COUNT(p.LibraryID) AS total FROM products p
GROUP BY p.LibraryID
UNION
SELECT t.LibraryID, COUNT(t.LibraryID) AS total FROM types t
GROUP BY t.LibraryID
)
o INNER JOIN Libraries l ON l.ID = o.LibraryID
WHERE l.UserID = 559
GROUP BY l.ID, l.LibraryName
ORDER BY l.LibraryName


This works fine if the nested counts return a value but doesn't if there are no matching libraries in the types or products table. How can I exclude the count for 0 or return the id, libraryname, 0 when there are no matching records in the products/types table?

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2007-09-28 : 04:52:45
[code]SELECT l.ID,
l.LibraryName,
COUNT(o.LibraryID) AS Recs
FROM Libraries AS l
LEFT JOIN (
SELECT LibraryID
FROM Products

UNION ALL

SELECT LibraryID
FROM Types
) AS o ON o.LibraryID = l.ID
WHERE l.UserID = 559
GROUP BY l.ID,
l.LibraryName
ORDER BY l.LibraryName[/code]


E 12°55'05.25"
N 56°04'39.16"
Go to Top of Page
   

- Advertisement -