ID Zip Room
----------- ---------- ------
317 94087 S105
318 94087 L603
1739 94404-1801 L603
1823 94401-2129 L603
1824 94401-2129 L603
2135 94404-1801 L603
2268 95136-1459 S604
2269 95136-1459 S604
3704 92673-6417 L402
4479 93454-9670 L402
4480 93454-9670 L402
4782 92395-4681 L402
4783 92395-4681 L402
4852 92886-4411 L402
4853 92886-4411 L402
4959 92673-6417 L402
5153 91773-4028 L402
5202 91773-4028 L402
5211 91765-2959 L402
5212 91765-2959 L402
5388 92336-0605 L402
5392 92336-0605 L402
5727 92870 L402
5728 92870 L402
5831 92557 L402
5916 92557 L402
如何选择具有相同拉链但不同房间的ID?
在上表中,我希望结果为:
ID Zip Room
----------- ---------- ------
317 94087 S105
318 94087 L603
使用SQL Server 2008
答案 0 :(得分:10)
您可以使用EXISTS
:
SELECT ID, Zip, Room
FROM dbo.Table t1
WHERE EXISTS
(
SELECT 1 FROM dbo.Table t2
WHERE t2.Zip = t1.Zip
AND t2.Room <> t1.Room
)
答案 1 :(得分:5)
select *
from table t1
join table t2
on t1.Zip = t2.Zip and t1.Room <> t2.Room
答案 2 :(得分:0)
您可以使用窗口聚合函数MIN()
和MAX()
来相应地获取每Room
的最小值和最大值Zip
,然后仅选择那些行的WITH MinMax AS (
SELECT
*,
MinRoom = MIN(Room) OVER (PARTITION BY Zip),
MaxRoom = MAX(Room) OVER (PARTITION BY Zip)
FROM atable
)
SELECT
ID,
Zip,
Room
FROM MinMax
WHERE MinRoom <> MaxRoom
;
行价值观不同。这里:
{{1}}