我试图只选择2个不同的列来确定我的查询中显示的记录。列userid能够拥有多个房屋,这意味着当前可以多次出现用户ID。但是,我只关心它们是否是房子的特定颜色,所以我希望userid列与House列相同,而其余行可以保持为该行内的任何内容。
Select UserID, House, NumOfPpl, NumOfCars
from people
结果:
userID House NumOfPpl NumOfCars
-----------------------------------
1a red 3 2
1a blue 1 1
1a red 5 4
1a green 2 3
1a blue 1 3
2a red 3 3
3a green 4 6
3ab red 2 1
3ab red 5 5
3ab blue 2 1
需要:
userID House NumOfPpl NumOfCars
----------------------------------
1a red 3 2
1a blue 1 1
1a green 2 3
2a red 3 3
3a green 4 6
3ab red 2 1
3ab blue 2 1
我已经使用cte来删除重复的用户ID,但是如何在用户ID中删除重复的内容?
;with cte AS (
select userid,
house,
numofppl,
numofcars,
row_number() OVER(partition by userID order by house) AS rowcounter
FROM people
)
SELECT userid, house, numofppl, numofcars
from cte
WHERE rowcounter = 1
答案 0 :(得分:4)
将值放在您想要唯一的partition by
中。所以,我认为你想要userID, house
。 order by
没有什么区别:
with cte AS (
select p.*
row_number() over (partition by userID, house order by house) AS seqnum
from people p
)
select userid, house, numofppl, numofcars
from cte
where seqnum = 1;
答案 1 :(得分:0)
此查询可行。
SELECT * FROM people 房子= ANY(SELECT DISTINCT house FROM people);
尝试这个我想这应该有用。