SQL Server在多个元组中选择具有不同ID但相同值的记录

时间:2018-09-07 18:26:32

标签: sql-server

我有一个表,该表具有位置ID,产品ID和技术ID。我希望能够在数据中找到一个实例,其中一个位置具有两个不同技术ID的不同产品ID。这是我要查找的示例。

|Location ID | Product ID | Tech ID |
+------------+------------+---------+
|Location 1  | Product 1  |Tech ID 1|
|Location 1  | Product 1  |Tech ID 2|
|Location 2  | Product 1  |Tech ID 1|
|Location 2  | Product 2  |Tech ID 2|
|Location 3  | Product 1  |Tech ID 1|
|Location 3  | Product 1  |Tech ID 2|
|Location 4  | Product 3  |Tech ID 1|
|Location 4  | Product 3  |Tech ID 2|

在此示例中,由于产品不同,我想查找位置2。任何帮助表示赞赏,谢谢。

2 个答案:

答案 0 :(得分:0)

--SELECT THE DISTINCT Location ID from the sub query
SELECT DISTINCT x.[Location ID]
FROM
(
   --Sub query to Group by LocationId and Product ID, along with Row_Number
   --TO get an integer value of which records have more than one 
   --when grouped by locationId and productId, if Row Number > 1 it means there are more than one record
   --for same location id (so there are different products)
   SELECT [Location ID], ROW_NUMBER() OVER(PARTITION BY [Location ID] ORDER BY [Location ID]) AS 
[RowNumber]
   FROM TABLE
   GROUP BY [Location ID], [Product ID]
) AS x
WHERE x.[RowNumber] > 1

答案 1 :(得分:0)

这是一种应该表现出色的简单方法:

SELECT * FROM MyTable t1
WHERE EXISTS(SELECT * FROM MyTable 
  WHERE t1.LocationID=t2.LocationId
  AND t1.ProductID<>t2.ProductID
  AND t1.TechID<>t2.TechID
)