如何比较sql中表的两列?

时间:2015-01-27 06:38:15

标签: sql sql-server sql-server-2008

在表格中有两列:

 -----------     
 | A  |  B |
 -----------
 | 1  |  5 |
 | 2  |  1 |
 | 3  |  2 |
 | 4  |  1 |
 -----------

想要一张表,如果A = B则

  -------------------
  |Match  | notMatch|
  -------------------
  |  1    |    5    |
  |  2    |    3    |
  | Null  |    4    |
  -------------------

我该怎么做?

我尝试过显示匹配部分的内容

select distinct C.A as A from Table c  inner join Table d on c.A=d.B

4 个答案:

答案 0 :(得分:2)

试试这个:

;WITH TempTable(A, B) AS(
    SELECT 1, 5 UNION ALL
    SELECT 2, 1 UNION ALL
    SELECT 3, 2 UNION ALL
    SELECT 4, 1
)
,CTE(Val) AS(
    SELECT A FROM TempTable UNION ALL
    SELECT B FROM TempTable
)
,Match AS(
    SELECT
        Rn = ROW_NUMBER() OVER(ORDER BY Val),
        Val
    FROM CTE c
    GROUP BY Val
    HAVING COUNT(Val) > 1
)
,NotMatch AS(
    SELECT
        Rn = ROW_NUMBER() OVER(ORDER BY Val),
        Val
    FROM CTE c
    GROUP BY Val
    HAVING COUNT(Val) = 1
)
SELECT
    Match   =   m.Val, 
    NotMatch=   n.Val
FROM Match m
FULL JOIN NotMatch n
    ON n.Rn = m.Rn

答案 1 :(得分:0)

尝试使用EXCEPT,MINUS和INTERSECT语句。 像这样:

SELECT A FROM TABLE1 INTERSECT SELECT B FROM TABLE1;

答案 2 :(得分:0)

你可能想要这个:

SELECT DISTINCT 
    C.A as A 
FROM 
    Table c  
LEFT OUTER JOIN 
    Table d 
    ON 
    c.A=d.B
WHERE
    d.ID IS NULL

请注意,我使用d.ID作为示例,因为我没有看到您的架构。另一种方法是明确说明d.columns IS NULL子句中的所有WHERE

答案 3 :(得分:0)

你的要求有点 - 让我们称之为 - 有趣。这是一种使用pivot来解决它的方法。就个人而言,我会选择不同的表结构和另一种选择数据的方式:

测试数据:

DECLARE @t table(A TINYINT, B TINYINT)

INSERT @t values
(1,5),(2,1),
(3,2),(4,1)

查询:

;WITH B AS
(
  ( SELECT A FROM @t
    EXCEPT 
    SELECT B FROM @t)
   UNION ALL
  ( SELECT B FROM @t
    EXCEPT 
    SELECT A FROM @t)
), A AS
(
  SELECT A val
  FROM @t
  INTERSECT
  SELECT B
  FROM @t
), combine as
(
  SELECT val, 'A' col, row_number() over (order by (select 1)) rn FROM A
  UNION ALL
  SELECT A, 'B' col, row_number() over (order by (select 1)) rn
  FROM B
)
SELECT [A], [B]
FROM combine
PIVOT (MAX(val) FOR [col] IN ([A], [B])) AS pvt

结果:

A    B
1    3
2    4
NULL 5