我有这样的数据。有时候有2条记录,1条带有邮寄地址&非邮寄地址,有时只有1条记录,可以是邮寄地址或非邮寄地址。
UniqueID,FirstName,LastName,DOB,House Number,City,State,Mailing
4444,George,Jetson,10/10/55,800,Orbit City,Space,0
4444,George,Jetson,10/10/55,555,Orbit City,Space,1
5555,Fred,Flintstone,12/12/04,88,Bedrock,PH,0
5555,Fred,Flintstone,12/12/04,100,Bedrock,PH,1
6666,Barney,Rubble,7/7/07,999,Bedrock,PH,0
7777,Jonny,Quest,5/30/64,343,Action City,KS,1
我正在尝试创建一个查询,为每个人返回1行,如果存在则更喜欢邮件地址。理想情况下,查询将返回这些记录
4444,George,Jetson,10/10/55,555,Orbit City,Space,1
5555,Fred,Flintstone,12/12/04,100,Bedrock,PH,1
6666,Barney,Rubble,7/7/07,999,Bedrock,PH,0
7777,Jonny,Quest,5/30/64,343,Action City,KS,1
有没有人有任何建议,基于我一直在阅读的一些文章我在想也许我需要有一个子查询?在我正在阅读的例子中,我被困在OVER PARTITION BY部分,或者我应该有某种IF声明?我对SQL很陌生,所以感谢任何方向或帮助。
答案 0 :(得分:2)
使用SQL-Server,您可以使用ROW_NUMBER
,例如使用CTE:
WITH CTE AS
(
SELECT UniqueID, FirstName, LastName, DOB, [House Number], City, State, Mailing,
rn = ROW_NUMBER() OVER (PARTITION BY UniqueID ORDER BY Mailing DESC)
FROM dbo.TableName
)
SELECT UniqueID, FirstName, LastName, DOB, [House Number], City, State, Mailing,
FROM CTE
WHERE rn = 1
这是一个小提琴:http://sqlfiddle.com/#!3/886b0/5/0
UNIQUEID FIRSTNAME LASTNAME DOB HOUSE NUMBER CITY STATE MAILING
4444 George Jetson October, 10 1955 00:00:00+0000 555 Orbit City Space 1
5555 Fred Flintstone December, 12 2004 00:00:00+0000 100 Bedrock PH 1
6666 Barney Rubble July, 07 2007 00:00:00+0000 999 Bedrock PH 0
7777 Jonny Quest May, 30 1964 00:00:00+0000 343 Action City KS 1
答案 1 :(得分:2)
您还可以将此查询表达为:
select *
from tablename t
where mailing = 1
union all
select *
from tablename t
where not exists (select 1 from tablename t2 where t2.uniqueid = t.uniqueid);