tsql-从一组行中提取第一个匹配项

0h4hbjxa  于 2021-08-09  发布在  Java
关注(0)|答案(1)|浏览(382)

我有一个简单的场景,其中一个表存储有关用户使用的卡以及这些卡是否在系统中注册(存在)的数据。我已经申请了 ROW_NUMBER 把他们也分组 SELECT User, CardId, CardExists, ROW_NUMBER() OVER (PARTITION BY User) AS RowNum From dbo.CardsInfo ```
User | CardID | CardExists | RowNum

A | 1 | 0 | 1
A | 2 | 1 | 2
A | 3 | 1 | 3

B | 4 | 0 | 1
B | 5 | 0 | 2
B | 6 | 0 | 3
B | 7 | 0 | 4

C | 8 | 1 | 1
C | 9 | 0 | 2
C | 10 | 1 | 3

现在在上面,我需要根据下面的两个规则过滤掉用户卡
如果在用户注册的卡中,系统中存在多张卡,则取第一张卡。因此,对于用户a,将返回cardid2,对于用户c,将返回cardid=8
另外,如果系统中没有该用户的卡(已注册),则只使用第一张卡。因此,对于用户b,它应该返回cardid=4
因此,最终返回集应该是-

User | CardID | CardExists | RowNum

A | 2 | 1 | 2

B | 4 | 0 | 1

C | 8 | 1 | 1

如何在sql中进行过滤?
谢谢
igsr9ssn

igsr9ssn1#

您可以使用:

SELECT ci.*
FROM (SELECT User, CardId, CardExists,
             ROW_NUMBER() OVER (PARTITION BY User ORDER BY CardExists DESC, CardId) AS RowNum
      FROM dbo.CardsInfo ci
     ) ci
WHERE seqnum = 1;

您还可以通过聚合来实现这一点:

select user,
       max(cardexists) as cardexists,
       coalesce(min(case when cardexists = 1 then cardid end),
                min(card(cardid)
               ) as cardid
from cardsinfo
group by user;

或者,如果有单独的用户表:

select ci.*
from users u cross apply
     (select top (1) ci.*
      from cardinfo ci
      where ci.user = u.user
      order by ci.cardexists desc, cardid asc
     ) ci

相关问题