不提供任何SQL的道歉,我的SQL技能是基本的,我之前没有遇到过这种要求。
使用如下表格:
表格
id size batch code product code
---------------------------------------
1 91 55555 BigD Red
2 94 55555 BigD Red
3 91 44444 BigD Blue
4 92 44444 BigD Blue
5 93 44444 BigD Blue
6 94 44444 BigD Blue
7 91 33333 BigD Orange
8 94 33333 BigD Orange
如何构造一个返回以下结果的SQL语句?
结果
id size batch code product code
--------------------------------------
1 91 55555 BigD Red
7 91 33333 BigD Orange
记录按产品代码分组。在每个组中,我只查找 NOT 包含大小为“92”的组...并希望显示每个组中大小为“91”的单个记录。大小91始终存在于每个组中。
答案 0 :(得分:1)
这是使用not exists
的通用版本:
select *
from yourtable y1
where size = 91 and not exists (
select 1
from yourtable y2
where y1.productcode = y2.productcode and y2.size = 92)
答案 1 :(得分:0)
您正在NOT EXISTS
NOT IN
select *
from myTable t
where t.size=91
and not exists (select 1 from myTable t1
where t1.productCode=t2.productCode
and t1.size=92)
答案 2 :(得分:0)
不确定MySql,但这适用于Sql server:
SELECT T1.Id, T1.Size, T1.BatchCode, T1.ProductCode
FROM Table T1
LEFT JOIN
(
SELECT ProductCode
FROM Table
WHERE Size = 92
) T2 ON T1.ProductCode = T2.ProductCode
WHERE T1.Size = 91
AND T2.ProductCode IS NULL
答案 3 :(得分:0)
Select * from myTable t
Where id =
(Select Min(id) from myTable -- < need this to ensure only one
where product code = t.product code
and size = 91
and not exists
(Select * from myTable
Where product code = t.product code
and size = 92))
答案 4 :(得分:0)
select * from myTable where size!=92
group by productcode having size=91