简体   繁体   中英

Return value if Row(Record) does not Exist in SQL SERVER

I have a table named as 'Banners' with following data and structure:

ID  Name   Enabled SectionID Slot

112 kabob     1      231      6 
198 Omega-5   1      231      1 
165 eeee      1      231      3 
171 iiii      1      231      3 
172 jjjj      1      231      3
113 cooked    1      231      4
114 coconut   1      231      5 

Note : There can be in all 6 slots (1 to 6) in Slot column, but i have not added a record for slot 2. ie row does not exist for slot 2.

Query :

SELECT DISTINCT Slot AS '231' FROM Mercola_Banners WHERE      
 SectionID = 231 and ENABLED = 1    
 GROUP BY slot  
 HAVING COUNT(1) <=15

Result i get:

  231 
1  1
2  3
3  4
4  5
5  6

As, i have not added any record for slot 2 it does not show in result. but i want that slot in my result. As it does not have any record for slot 2. OR Count <15. As shown below.

Expected Result :

  231 
1  1
2  2
3  3
4  4
5  5
6  6

This is too long for a comment.

Why are you bothering with such a complicated query? Why not just do:

select n as [231]
from (select 1 as n union all select 2 union all select 3 union all select 4 union all
      select 5 union all select 6
     ) n

I don't see what the results you want really have to do with the data in the tables.

EDIT:

If I understand correctly, you still do want to apply the other criteria. You are saying that 2 meets the criteria because there are fewer than 15 rows. But it doesn't make it into the output because there are no rows. Here is one solution to this problem:

SELECT n.n AS [231]
FROM (select 1 as n union all select 2 union all select 3 union all select 4 union all
      select 5 union all select 6
     ) n LEFT JOIN
     Mercola_Banners mb
     ON n.n = mb.slot and mb.SectionID = 231 and mb.ENABLED = 1    
GROUP BY n.n  
HAVING COUNT(mb.slot) <= 15

The clean way is to have a table, for example called slots Then you can do the following query:

select slotid, (select count(*) from banners b where b.slot = slotid) as count 
from slots.

This way if you add more slots in the future, you only need to add them to that table.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM