获取每个ID列的最大值

时间:2018-04-04 18:05:08

标签: sql sql-server-2012

在下面的查询中,我希望获得每个USERID的SEQNBR字段的MAX值,其中该USERID没有STATUS值为'CLE'的行。

我能够检索每个USERID的MAX SEQNBR行,但是它不排除USERID,它们在表中有一行,值为“CLE”。

由于查询最终会运行的环境受到限制,我想避免在SELECT子句中使用公用表表达式(CTE)和子查询。

SELECT A.USERID, (CONVERT(CHAR(10),A.TEST_DT,121))AS 'TEST_DATE', A.TYPE_CD, 
 (CONVERT(CHAR(10),A.NEXT_TEST_DT,121))AS 'EXPIRE_DATE', B.STATUS1, 
 B.MGR_CLR, B.COMMENT, C.COMPANY, D.DESCR, E.DESCR, 
 F.LAST_NAME, F.FIRST_NAME, B.SEQNBR 
FROM ((((((TEST_PLACEMENT A 
LEFT OUTER JOIN  TEST_STATUS B ON  B.USERID = A.USERID AND B.TEST_DT 
= A.TEST_DT ) 
LEFT OUTER JOIN  (PS_JOB C INNER JOIN PS_EMPLMT_SRCH_QRY C1 ON (C.USERID = 
C1.USERID AND C.EMPL_RCD = C1.EMPL_RCD )) ON  
C.USERID = A.USERID ) 
LEFT OUTER JOIN  PS_JOBCODE_TBL D ON  D.JOBCODE = C.JOBCODE ) 
LEFT OUTER JOIN  PS_DEPARTMENT_VW E ON  E.DEPTID = C.DEPTID ) 
LEFT OUTER JOIN  (PS_JOB G INNER JOIN PS_EMPLMT_SRCH_QRY G1 ON (G.USERID = 
 G1.USERID AND G.EMPL_RCD = G1.EMPL_RCD )) ON  
 G.POSITION_NBR = C.REPORTS_TO AND G.EFFDT = (SELECT MAX( H.EFFDT) 
 FROM PS_JOB H, PS_EMPLMT_SRCH_QRY H1 
 WHERE H.USERID = H1.USERID 
 AND H.EMPL_RCD = H1.EMPL_RCD 
 AND ( G.POSITION_NBR = H.POSITION_NBR )) ) 
LEFT OUTER JOIN  (PS_NAMES F INNER JOIN PS_PERALL_SEC_QRY F1 ON (F.USERID = 
F1.USERID )) ON  F.USERID = A.USERID ) 
WHERE ( ( 
 C.JOB_INDICATOR = 'P' 
 AND B.SEQNBR = 
  (SELECT MAX(BB.SEQNBR) FROM TEST_STATUS BB
   WHERE  BB.USERID = B.USERID AND BB.STATUS1 <> 'CLE')
   --GROUP BY BB.STATUS1)
 AND G.EFFSEQ = 
    (SELECT MAX(G_ES.EFFSEQ) FROM PS_JOB G_ES 
    WHERE G.USERID = G_ES.USERID 
      AND G.EMPL_RCD = G_ES.EMPL_RCD 
      AND G.EFFDT = G_ES.EFFDT) )))

有问题的代码是:

  (AND B.SEQNBR = 
  (SELECT MAX(BB.SEQNBR) FROM TEST_STATUS BB
  WHERE  BB.USERID = B.USERID AND BB.STATUS1 <> 'CLE')
  --GROUP BY BB.STATUS1)) 

这是现在主要查询内容的示例数据:

enter image description here

以下是所需的结果(基于上面的原始示例):

enter image description here

正如您所看到的,USERID的1和3已被删除,基于它们各自具有'CLE'状态的行,并且USERID 5与SEQNBR 37的行被删除,因为它不是该USERID的MAX SEQNBR (SEQNBR 38用于USERID 5)。

2 个答案:

答案 0 :(得分:1)

您需要测试所有行

library(dplyr)
data %>%
    mutate(
        txtype = case_when(
            NDC %in% c("11111", "22222", "33333") ~ "typeA",
            NDC %in% c("44444", "55555") ~ "typeB"
        )
    )

答案 1 :(得分:0)

And b.seqnbr=(Select max(bb.seqnbr) from     TEST_STATUS bb
Where bb.user_id not in (
Select t2.user_id from TEST_STATUS t2 where t2.status='CLE'
)
and bb.user_id=b.user_id
Group by bb.user_id)