好的,我需要一个T-SQL大师。
我有一个名为PackageStoreEvents的表,它有一个packageid,storecode和一个eventcode字段。我想返回商店代码2406的packageid值,其中eventcode = 6的计数为0.
我该怎么做?
我坚持这个。
感谢您的帮助
答案 0 :(得分:7)
尝试:
select packageid
from PackageStoreEvents
where storecode = 2406
group by packageid
having sum(case eventcode when 6 then 1 else 0 end)=0;
用于单遍查询。
答案 1 :(得分:6)
这不是很漂亮,但应该有用。您将连接保留在同一个表中,包括连接条件中的事件代码,断言右表没有IS NULL
的行,然后执行DISTINCT以避免返回的许多行。
SELECT DISTINCT p1.packageid
FROM PackageStoreEvents p1
LEFT JOIN
PackageStoreEvents p2
ON p1.packageid = p2.packageid
AND p1.storecode = p2.storecode
AND p2.eventcode = 6
WHERE p2.packageid IS NULL
AND p1.storecode = 2406
答案 2 :(得分:2)
假设我正确理解了这个问题,我会使用类似的东西:
-- PackageStoreEvents (packageid, storecode, eventcode)
SELECT DISTINCT packageid
FROM PackageStoreEvents r
WHERE storecode = 2406
AND NOT EXISTS ( SELECT *
FROM PackageStoreEvents cnt
WHERE cnt.packageid = r.packageid
AND cnt.storecode = r.storecode
AND cnt.eventcode = 6)
答案 3 :(得分:1)
SELECT packageid
FROM
PackageStoreEvents p1
WHERE storecode = 2406
AND NOT EXISTS (SELECT * FROM PackageStoreEvents p2
WHERE p1.packageid = p2.packageid
AND p1.storecode = p2.storecode
AND p2.eventcode = 6)
答案 4 :(得分:-2)
也许这个?:
SELECT PackageID
FROM PackageStoreEvents
WHERE Storecode = 2406 and EventCode = 6
GROUP BY PackageID
HAVING COUNT(EventCode) = 0