【问题标题】:TO find out same student is associated with how many subjects in different group找出同一个学生与不同组中有多少科目相关联
【发布时间】:2019-08-03 10:27:40
【问题描述】:

我有下表,需要提取那些相同值与多个不同 GroupId 相关联的记录。如果相同的值在相同的 GroupId 下重复,则不需要获取。

GroupId Value
11       AAA
11       AAA
11       BBB
22       AAA
22       CCC
22       CCC
33       AAA
33       DDD
33       BBB

我已经用Count(*)Having Count(*)>1 尝试过,但没有给我想要的输出

我需要的输出如下,它告诉相同的值与不同的GroupId 相关联。在这里,如果相同的值在相同的GroupId 中重复,我并不担心。我只需要在多个GroupId 中可用的值。

期望的输出-

Column  Value   GroupId
1        AAA    11
1        AAA    22
1        AAA    33
2        BBB    22
2        BBB    33

【问题讨论】:

    标签: sql-server sql-query-store sql-rank


    【解决方案1】:

    你可以试试这个。

    ; WITH CTE AS (  
        SELECT DISTINCT GROUPID, VALUE FROM @TAB 
    )  
    , CT AS (  
        SELECT DENSE_RANK() OVER (PARTITION BY VALUE ORDER BY GROUPID, VALUE) AS SLNO, * FROM CTE
    )  
    SELECT DENSE_RANK() OVER ( ORDER BY VALUE) AS [COLUMN], * FROM CTE 
        WHERE VALUE IN (SELECT  VALUE FROM CT WHERE SLNO>1)
    

    【讨论】:

      【解决方案2】:

      存在:

      select distinct t.*
      from tablename t
      where exists (
        select 1 from tablename
        where value = t.value and groupid <> t.groupid
      )
      order by t.value, t.groupid
      

      请参阅demo
      结果:

      > GroupId | Value
      > ------: | :----
      >      11 | AAA  
      >      22 | AAA  
      >      33 | AAA  
      >      11 | BBB  
      >      33 | BBB  
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-04-09
        • 2013-02-13
        • 2016-01-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多