[英]SQL Server : select values from multiple rows when one row met condition
我有一個表products
,一個特定的產品可能包含不同的模型,模型0代表基本模型:
Select *
From products
Where product_number = 12345;
結果:
id made_by product_number model
----------------------------------
122 U123 12345 0
123 U123 12345 1
124 U552 12345 2
現在,我只想查找基本模型(model = 0) made_by
值在某些模型中不同的產品?
在這個例子中,我肯定有興趣獲得此產品12345的結果。
我想到的是選擇與眾不同的方法,但是也許有更好的方法?
你可以使用一個exists
子查詢,檢查是否有不同made_by
為同一product_number
:
select product_number
from YourTable yt1
where yt1.model = 0
and exists
(
select *
from YourTable yt2
where yt1.product_number = yt2.product_number
and yt2.made_by <> yt1.made_by
)
存在是執行此操作的更好方法,但您也可以通過以下方式進行自我join
select t1.*
from products t1
inner join
products t2
on
t1.product_number=t2.product_number
and t1.made_by<>t2.made_by
and t1.model<>0
and t2.model=0;
樣本數據
從產品中選擇*;
+-----+---------+----------------+-------+
| id | made_by | product_number | model |
+-----+---------+----------------+-------+
| 122 | U123 | 12345 | 0 |
| 123 | U123 | 12345 | 1 |
| 124 | U552 | 12345 | 2 |
| 125 | U5 | 12346 | 0 |
| 126 | U5 | 12346 | 1 |
| 127 | U6 | 12347 | 0 |
| 128 | U7 | 12347 | 1 |
+-----+---------+----------------+-------+
產量
+-----+---------+----------------+-------+
| id | made_by | product_number | model |
+-----+---------+----------------+-------+
| 124 | U552 | 12345 | 2 |
| 128 | U7 | 12347 | 1 |
+-----+---------+----------------+-------+
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.