通过ID选择最小Seq编号

时间:2019-06-10 18:17:44

标签: sql sql-server sql-server-2014

只需尝试编写一个简单的查询,以获取CNTCT_SEQ_NUM最小且CONTACT_NAME不为空的行(每个VENDOR_ID)。

这是我写的:

SELECT VENDOR_ID, MIN(CNTCT_SEQ_NUM) AS CNTCT_SEQ_NUM , CONTACT_NAME
FROM PS_VENDOR_CNTCT
WHERE VENDOR_ID IN ('ERSUT', 'MOOREA')
AND CONTACT_NAME <> ''
GROUP BY CONTACT_NAME, VENDOR_ID

当前结果:

VENDOR_ID   CNTCT_SEQ_NUM   CONTACT_NAME
ERSUT       19              V Smith
ERSUT       4               T Peterman
ERSUT       2               I GANCE
ERSUT       8               R FISHER
MOOREA      2               S DALY
MOOREA      4               B SLAUTEN
MOOREA      1               N BLAKELY

预期结果将是:

VENDOR_ID   CNTCT_SEQ_NUM   CONTACT_NAME
ERSUT       2               I GANCE
MOOREA      1               N BLAKELY

3 个答案:

答案 0 :(得分:2)

试试这个-

SELECT A.* FROM PS_VENDOR_CNTCT A
INNER JOIN
(
    SELECT VENDOR_ID,MIN(CNTCT_SEQ_NUM) CNTCT_SEQ_NUM
    FROM PS_VENDOR_CNTCT
    GROUP BY VENDOR_ID
)B ON A.VENDOR_ID = B.VENDOR_ID
AND A.CNTCT_SEQ_NUM = B.CNTCT_SEQ_NUM

答案 1 :(得分:1)

一个相关的子查询解决了这个问题:

select vc.*
from PS_VENDOR_CNTCT vc
where vc.CNTCT_SEQ_NUM = (select min(vc2.CNTCT_SEQ_NUM)
                          from PS_VENDOR_CNTCT vc2
                          where vc2.VENDOR_ID = vc.VENDOR_ID and
                                vc2.CONTACT_NAME <> ''
                         );

为了提高性能,您可以尝试在(VENDOR_ID, CONTACT_NAME, CNTCT_SEQ_NUM)上建立索引。这将涵盖子查询,尽管所有索引记录仍将需要扫描。

答案 2 :(得分:1)

您似乎不需要MIN(),但需要窗口分析功能,例如ROW_NUMBER()

SELECT DISTINCT Q.VENDOR_ID, Q.CONTACT_NAME, Q.CNTCT_SEQ_NUM
  FROM
  (
  SELECT P.*, 
         ROW_NUMBER() OVER 
                     (PARTITION BY VENDOR_ID ORDER BY CNTCT_SEQ_NUM) AS RN
    FROM PS_VENDOR_CNTCT P
   WHERE VENDOR_ID IN ('ERSUT', 'MOOREA')
     AND CONTACT_NAME <> ''     
   ) Q
  WHERE Q.RN = 1