如果表中的两列具有相同的值,则获取单行

时间:2012-10-12 13:05:16

标签: sql sql-server

我有一个包含调用者和被调用者的表,其中包含以下值

caller callee
999 888
888 999
999 555
555 333
555 999

现在我想只返回单行

caller1    caller2  count 
999        888      2
999        555      1
555        333      1
555        999      2

1 个答案:

答案 0 :(得分:6)

SELECT CASE
         WHEN caller < callee THEN callee
         ELSE caller
       END      AS caller1,
       CASE
         WHEN caller < callee THEN caller
         ELSE callee
       END      AS caller2,
       Count(*) AS [Count]
FROM   YourTable
GROUP  BY CASE
            WHEN caller < callee THEN callee
            ELSE caller
          END,
          CASE
            WHEN caller < callee THEN caller
            ELSE callee
          END