Windows函数的正确语法

时间:2018-09-21 20:15:57

标签: sql sql-server-2014

我有以下查询可与基表PS_GHS_HS_IMMUN一起正常工作,但是当我离开OUTER JOIN时,我得到了很多重复,我想知道由于使用Windows而语法是否正确功能。

PS_GHS_HS_IMMUN和PS_JOB之间的键是EMPLID和EMPL_RCD,因此,除非查询的格式不正确,否则我不希望重复。

SELECT A.EMPLID, A.EMPL_RCD, EXAM_DT, IMMUN_CODE, RN
FROM ( 
          SELECT ROW_NUMBER() OVER (PARTITION BY EMPLID, EXAM_DT, IMMUN_CODE ORDER BY EMPLID DESC) AS RN
            , EMPLID
            , EMPL_RCD
            , EXAM_DT
            , IMMUN_CODE
FROM PS_GHS_HS_IMMUN AS RN1 ) AS A
LEFT OUTER JOIN PS_JOB B ON A.EMPLID = B.EMPLID AND A.EMPL_RCD = B.EMPL_RCD 
WHERE A.RN = 1
GROUP BY A.EMPLID,A.EXAM_DT, A.IMMUN_CODE, A.EMPL_RCD, A.RN
ORDER BY A.EXAM_DT

仅在查询语法格式是否正确方面寻求指导。

样本数据:

EMPLID  EMPL_RCD    EXAM_DT                   IMMUN_CODE    RN
015     1           2018-09-19 00:00:00.000   FLDD          1
015     1           2018-09-19 00:00:00.000   FLDD          1
015     0           2018-09-19 00:00:00.000   FLDD          2
015     0           2018-09-20 00:00:00.000   PREV          1
015     1           2018-09-20 00:00:00.000   PREV          2
015     1           2018-09-20 00:00:00.000   PREV          2
015     1           2018-09-20 00:00:00.000   TDAB          1
015     1           2018-09-20 00:00:00.000   TDAB          1
015     0           2018-09-20 00:00:00.000   TDAB          2
015     0           2018-09-20 00:00:00.000   TSPS          1
015     1           2018-09-20 00:00:00.000   TSPS          2
015     1           2018-09-20 00:00:00.000   TSPS          2

1 个答案:

答案 0 :(得分:1)

您仅从第一张表中选择列。毫无疑问,第二张表中有重复的匹配项。

因为您正在子查询中计算rn,所以您将获得“第一”行以及多个匹配项。

我怀疑您的意图可能更多是从 second 表返回一行(这只是一个猜测):

SELECT ghi.EMPLID, ghi.EMPL_RCD, ghi.EXAM_DT, ghi.IMMUN_CODE
FROM PS_GHS_HS_IMMUN ghi LEFT OUTER JOIN
     (SELECT j.*,
             ROW_NUMBER() OVER (PARTITION BY j.EMPLID, j.EMPL_RCD ORDER BY ?) as seqnum  -- ? because I don't know which column
      FROM PS_JOB j
     ) 
     ON ghi.EMPLID = j.EMPLID AND ghi.EMPL_RCD = j.EMPL_RCD AND j.seqnum = 1
GROUP BY ghiEMPLID, ghi.EXAM_DT, ghi.IMMUN_CODE, ghi.EMPL_RCD
ORDER BY ghi.EXAM_DT;

该查询不需要GROUP BY。但是您正在构建的查询可能需要它。