通过仅获取不同的列来过滤数据

时间:2013-01-11 22:06:17

标签: sql sql-server tsql

我有一个查询

SELECT *
FROM tblMyTable

返回这些结果:

ID | TypeID | Name
----------------------------------
1DF6EAA0-D0EC-4E4D-9E6B-1779F0E42A82 | 8518A117-F032-61E6-EF15-1917F5B4E795 | AAA
7BB627EC-16CE-40DA-9CC0-A1861277988D | 8518A117-F032-61E6-EF15-1917F5B4E795 | BBB
25B68C46-C03E-4C1F-94BC-7A371B2F1AC3 | DBE7A7EF-5B97-448C-0D2E-5C0C2155A2FA | CCC
AD1A8990-4A57-4F95-BCBD-6112111782B0 | CAE4D031-2C02-2BB8-5D15-FF865A24AD55 | DDD
94C24A30-18EF-471E-8984-6D165EAB566B | A7FE61B5-F4EB-6286-D3A6-72E458D8745C | EEE
D3A7F2E2-DAAF-B991-E41D-105EBB071323 | A7FE61B5-F4EB-6286-D3A6-72E458D8745C | FFF
3EBE7F2F-A05E-FC02-4AE3-27DF6D9A524E | A7FE61B5-F4EB-6286-D3A6-72E458D8745C | GGG

我想过滤结果,以便只有不同的TypeId,以便返回的结果是:

ID | TypeID | Name
----------------------------------
1DF6EAA0-D0EC-4E4D-9E6B-1779F0E42A82 | 8518A117-F032-61E6-EF15-1917F5B4E795 | AAA
25B68C46-C03E-4C1F-94BC-7A371B2F1AC3 | DBE7A7EF-5B97-448C-0D2E-5C0C2155A2FA | CCC
AD1A8990-4A57-4F95-BCBD-6112111782B0 | CAE4D031-2C02-2BB8-5D15-FF865A24AD55 | DDD
94C24A30-18EF-471E-8984-6D165EAB566B | A7FE61B5-F4EB-6286-D3A6-72E458D8745C | EEE

如何更改查询以执行此操作?

1 个答案:

答案 0 :(得分:4)

您可以申请row_number()

select id, typeid, name
from
(
  select id, typeid, name,
    row_number() over(partition by typeid order by typeid, name) rn
  from yourtable
) src
where rn =1

请参阅SQL Fiddle with Demo