使用Id字段进行不同的查询

时间:2015-10-15 15:16:07

标签: sql-server

在下表中,一个帐户可以有多个州值(我这里没有提供除州字段以外的所有地址字段)

注意:Id字段的类型为varchar。

Account  	        Id	                State
------------------      ------------------  ----------------
A1000	                1000	                MI
A1000	                1001             	MI
A1001	                1002	                CA
A1001	                1003	                CA
A1002	                1004	                DE
A1002	                1005	                PS


I want to get output like below i.e. distinct of Account,State and its corresponding Top1 Id

 Account  	        Id	                State
------------------      ------------------  ----------------
A1000	                1000	                MI
A1001	                1002	                CA
A1002	                1004	                DE
A1002	                1005	                PS

直到现在我自己无法形成任何查询。任何人都可以知道如何实现这一目标。

4 个答案:

答案 0 :(得分:0)

您可以使用ROW_NUMBER

;WITH CTE AS
(
    SELECT  *,
            RN = ROW_NUMBER() OVER(PARTITION BY Account, [State] ORDER BY Id)
    FROM dbo.YourTable
)
SELECT  Account,
        Id,
        [State]
FROM CTE
WHERE RN = 1;

答案 1 :(得分:0)

你会得到最小的id:

select Account, min(Id) as Id, State
from yourtable
group by Account, State

答案 2 :(得分:0)

select Account, MIN(Id), MIN(State)
FROM Account
GROUP BY Account

答案 3 :(得分:0)

尝试使用此查询:

SELECT  T.Account,
        T.Id,
        T.[State]
FROM (

SELECT  *, RN = ROW_NUMBER() OVER(PARTITION BY Account, [State] ORDER BY Id)
    FROM dbo.YourTable ) AS T
WHERE T.RN = 1;