Additional SQL Server features and topics not covered by specific categories
help with sql query to return existing and non-existent records.
When you use WHERE clause to filter data, then of course you will never see non-existent records in the final output. Because this clause is the initial filtering of the data that was retrieved in the FROM clause. This is all about finding the rows that need to be considered in the query.
What you need is to add the filter condition inside the aggregate function using CASE WHEN.
Please try something like this:
create table #idcase05n(idstyl varchar(18),idwhse varchar(18))
insert into #idcase05n values
('799941','FP'),('799941','FP'),('799941','FP'),
('799950','DP'),('799950','GP'),
('799981','GP'),('799981','SP')
SELECT idstyl,SUM(CASE WHEN idwhse = 'FP' THEN 1 ELSE 0 END) AS qty
FROM #idcase05n
GROUP BY idstyl
Best regards,
Cosmog Hong
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.