![](/img/trans.png)
[英]Sql Server Insert a new row if 1 value does not exist in dest table
[英]Return value if Row(Record) does not Exist in SQL SERVER
我有一個名為“橫幅”的表,其中包含以下數據和結構:
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
注意:“插槽”列中可以有所有6個插槽(1到6),但是我沒有為插槽2添加記錄。即,插槽2中不存在該行。
查詢:
SELECT DISTINCT Slot AS '231' FROM Mercola_Banners WHERE
SectionID = 231 and ENABLED = 1
GROUP BY slot
HAVING COUNT(1) <=15
結果我得到:
231
1 1
2 3
3 4
4 5
5 6
作為,我沒有為插槽2添加任何記錄,它也沒有顯示在結果中。 但我想在結果中使用該廣告位。 因為它沒有插槽2的任何記錄,否則計數<15。 如下所示。
預期結果 :
231
1 1
2 2
3 3
4 4
5 5
6 6
這個評論太長了。
為什么要打擾這么復雜的查詢? 為什么不做:
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
我看不到您想要的結果真正與表中的數據有什么關系。
編輯:
如果我理解正確的話,你仍然要應用的其他條件。 您說2
符合條件,因為少於15行。 但是由於沒有行,所以它沒有進入輸出。 這是解決此問題的一種方法:
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
干凈的方法是擁有一個表,例如稱為slot的表。然后,您可以執行以下查詢:
select slotid, (select count(*) from banners b where b.slot = slotid) as count
from slots.
這樣,如果將來添加更多插槽,則只需將它們添加到該表中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.