![](/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.