[英]SQL Server : how to select the rows in a table with the same value on a column but some exact values on another column for the grouped rows
I have this table with some sample data: 我有这个表有一些示例数据:
Supplier_ID Product_ID Stock
-----------------------------
1 272 1
1 123 5
1 567 3
1 564 3
2 272 4
2 12 3
2 532 1
3 123 4
3 272 5
I want to check the suppliers that have both products: 272
and 123
, so the result would be like: 我想查看同时包含两种产品的供应商:
272
和123
,结果如下:
Supplier_ID
-----------
1
3
You can use GROUP BY
and HAVING
: 您可以使用
GROUP BY
和HAVING
:
SELECT Supplier_ID
FROM your_tab
WHERE Product_ID IN (272, 123)
GROUP BY Supplier_ID
HAVING COUNT(DISTINCT Product_ID) = 2;
Try this code: 试试这段代码:
SELECT A.Supplier_ID FROM
(SELECT Supplier_ID FROM Your_Table WHERE Product_ID = 272) AS A
INNER JOIN
(SELECT Supplier_ID FROM Your_Table WHERE Product_ID = 123) AS B
ON A.Supplier_ID = B.Supplier_ID
This is how it works using set operations . 这是使用set操作的工作原理。 IMHO a too little used feature of databases.
恕我直言,数据库使用的功能太少了。
select Supplier_ID from table1 where product_id=272
intersect
select Supplier_ID from table1 where product_id=123
it produces as well 它也产生
Supplier_ID
1
3
By the way a distinct is not needed due to intersect delivers distinct rows. 由不同不需要因交叉的方式提供不同的行。
http://sqlfiddle.com/#!6/13b11/3 http://sqlfiddle.com/#!6/13b11/3
Try This Code: By Using Row_number() 试试这段代码:使用Row_number()
;WITH cte
AS (SELECT *,
Row_number()
OVER(
partition BY [Supplier_ID]
ORDER BY [Supplier_ID]) AS rn
FROM #Your_Table
WHERE Product_ID IN ( 272, 123 ))
SELECT DISTINCT Supplier_ID
FROM cte
WHERE rn > 1
OUTPUT : 输出 :
Supplier_ID
1
3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.