只获得重复记录的一次出现

时间:2016-06-20 11:55:52

标签: sql sql-server

select DISTINCT a.Schooldistricttown, a.Schooldistrictnum 
from [Legacy].[dbo].[MyTables] as a

它返回:

enter image description here

你能告诉我如何只出现一次a.Schooldistricttown吗? 我尝试过使用DISTINCTGROUP BY。但它不起作用。

注意:我还需要显示两个列。

2 个答案:

答案 0 :(得分:1)

有两个选项,如果您在Schooldistrictnum中获得哪个值无关紧要,那么用MAX()/MIN()分组将解决此问题:

SELECT a.Schooldistricttown,MAX(a.Schooldistrictnum)
from [Legacy].[dbo].[MyTables] a
GROUP BY a.Schooldistricttown

如果您关心,请使用ROW_NUMBER()

SELECT s.Schooldistricttown,s.Schooldistrictnum
FROM (
    SELECT a.Schooldistricttown,a.Schooldistrictnum,
           ROW_NUMBER() OVER(PARTITION BY a.Schooldistricttown ORDER BY a.<ORDER_COLUMN>) as rnk
    from [Legacy].[dbo].[MyTables]  a) s
WHERE s.rnk = 1

您需要将<ORDER_COLUMN>替换为您决定使用哪个值的实际列

答案 1 :(得分:0)

如果您想要所有Schooldistrictnum,请使用此

  SELECT DISTINCT 
    a.Schooldistricttown,
    (
        SELECT DISTINCT 
            ina.Schooldistrictnum + ', ' AS [text()]
        FROM 
            [Legacy].[dbo].[MyTables] as ina
        WHERE
            ina.Schooldistricttown =  a.Schooldistricttown
        FOR XML PATH ('')
     ) AS Schooldistrictnum 
   FROM [Legacy].[dbo].[MyTables] as a
相关问题