SQL窗口函数排序问题

时间:2018-01-29 16:53:27

标签: sql-server

我有一个可以拥有多个专业位置的数据集。我正在尝试根据以下标准选择一种专业:

  1. 如果Primary ='Y',则选择Primary over Boardcertified
  2. 如果Primary ='N'且Boardcertified ='Y',则选择Boardcertified
  3. 如果两个='N',则选择任一记录

    declare @t table(id int, location varchar(250), specialty varchar(250), boardcertified char, primaryspeciality char)
    
    insert into @t values(1, 'Dallas', 'Maternal', 'Y', 'N'),
                         (1, 'Dallas', 'Obstetrics', 'Y', 'Y'),
                         (2, 'Plano', 'Maternal', 'Y', 'N'),
                         (2, 'Plano', 'Peds', 'N', 'N'),
                         (3, 'Arlington', 'Peds', 'N', 'N'),
                         (3, 'Arlington', 'Maternal', 'Y', 'Y')
    
  4. 我一直试图通过窗口函数来解决这个问题,如下所示:

        select * from
        (
        select *, row_number()over(partition by id, location
                                   order by case when primaryspeciality = 'Y' then 1
                                             when boardcertified = 'Y' then 2
                                             end desc) as rn
    from @t)a
        where rn = 1
    

    这给了我以下结果:

        id    location   specialty    boardcertified   primaryspecialty 
        1       Dallas     Maternal     Y                 N
    

    我真正想要的是:

        id     location   specialty    boardcertified   primaryspecialty
        1       Dallas    Obstetrics      Y               Y
    

    由于达拉斯和Obstretics的primaryspecialty ='Y',我想要那个记录。我不确定我在这里做错了什么。

1 个答案:

答案 0 :(得分:1)

认为这就是你所追求的:

WITH CTE AS(
    SELECT *,
           ROW_NUMBER() OVER (PARTITION BY id, [location]
                              ORDER BY CASE primaryspeciality WHEN 'Y' THEN 0 ELSE 1 END,
                                       CASE boardcertified WHEN 'Y' THEN 0 ELSE 1 END,
                                       id) AS RN
    --If you want the id to be random each time when they are both 'Y' (as you said it could be any), replace id with NEWID()
    FROM @t)
SELECT *
FROM CTE
WHERE RN = 1;

请注意多个CASE表达式的使用。