确定样本是否包含多个ID的0行

时间:2018-12-27 18:27:32

标签: sql sql-server where

因此,我创建了一个简单的查询,该查询将传递所有订购了2个或更多苹果的OrdID

SELECT ordid 
FROM results 
WHERE ordid IN (12,24,53,21,41,51) 
AND product = 'apples' 
GROUP BY ordid 
HAVING COUNT(ordid) > 1

如何对包含0个苹果的OrdID进行此操作?(这不起作用,因为OrdID上没有苹果的产品,因此它传递了0行。)希望它列出所有具有<1种苹果产品的OrdID

SELECT ordid 
FROM results 
WHERE ordid IN (12,24,53,21,41,51)
AND product = 'apples' 
GROUP BY ordid 
HAVING COUNT(ordid) < 1

4 个答案:

答案 0 :(得分:2)

我无法在自己的机器上复制,但希望此查询有效:

SELECT ordid 
FROM results 
WHERE ordid in (12,24,53,21,41,51) 
GROUP BY ordid 
HAVING SUM(CASE WHEN product = 'apples' THEN 1 ELSE 0 END) < 1

答案 1 :(得分:0)

由于您要计算产品数量,因此我用COUNT()产品而不是订购编号切换了HAVING。

SELECT ordid
FROM results 
WHERE ordid in (12,24,53,21,41,51) and product = 'apples'
GROUP BY ordid 
HAVING COUNT(product) = 0

答案 2 :(得分:0)

您遇到的问题是,您正在选择FROM表(即,限制为那些行),而您要匹配的内容是表中没有的内容(即,排除那些行)。这些是相反的。

相反,将其翻转,以便您从“一组值”中选择,然后排除匹配的那些值:

SELECT ordid FROM (VALUES (12),(24),(53),(21),(41),(51)) AS ordids(ordid)
WHERE NOT EXISTS (
    SELECT * FROM results
    WHERE results.ordid = ordids.ordid
    AND results.product = 'apples'
)

这将返回ordid的结果,即使该值根本没有出现在results表中。

答案 3 :(得分:-1)

在不存在与slow.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { //speedSlow = true; timer.setDelay( 30 ); } }); 相关的行的地方,使用EXISTS()函数获取所有OrdID。