SQL列在2列上不同

时间:2017-08-30 00:45:03

标签: sql sql-server

有没有办法在两列的组合上查询不同的内容?让我们说我有下表,其中LinkedIds是来自同一个表的外键,下表将两者连接在一起。 我需要的是一种查询表以获取不同条目的方法,以便在查询图1时得到图2中的结果。

只要我回来一行,我会回到哪一行并不重要。无论如何用普通的SQL实现这个目的?

图1。

+----+-------------------+-------------------+
| Id | Table1_LinkedId_1 | Table1_LinkedId_2 |
+----+-------------------+-------------------+
|  1 | 15                | 48                |
|  2 | 48                | 15                |
|  3 | 1                 | NULL              |
|  4 | NULL              | 5                 |
|  5 | 12                | 51                |
+----+-------------------+-------------------+

图2。

+----+-------------------+-------------------+
| Id | Table1_LinkedId_1 | Table1_LinkedId_2 |
+----+-------------------+-------------------+
|  1 | 15                | 48                |
|  3 | 1                 | NULL              |
|  4 | NULL              | 5                 |
|  5 | 12                | 51                |
+----+-------------------+-------------------+

3 个答案:

答案 0 :(得分:2)

您可以创建表格的有序版本

select 
  id, 
  case when Table1_LinkedId_1 < Table1_LinkedId_2 then Table1_LinkedId_1 else Table1_LinkedId_2 end link1,
  case when Table1_LinkedId_1 < Table1_LinkedId_2 then Table1_LinkedId_2 else Table1_LinkedId_1 end link2
from links

然后你可以用它来重复数据删除

select 
  min(id) id,
  link1,
  link2
from 
(
      select 
        id, 
        case when Table1_LinkedId_1 < Table1_LinkedId_2 then Table1_LinkedId_1 else Table1_LinkedId_2 end link1,
        case when Table1_LinkedId_1 < Table1_LinkedId_2 then Table1_LinkedId_2 else Table1_LinkedId_1 end link2
      from links
) x
group by link1, link2

答案 1 :(得分:2)

这是一个选项......

.txt

结果...

IF OBJECT_ID('tempdb..#TestData', 'U') IS NOT NULL 
DROP TABLE #TestData;

CREATE TABLE #TestData (
    Id INT NOT NULL PRIMARY KEY,
    Link1 INT NULL,
    Link2 INT NULL 
    );
INSERT #TestData (Id, Link1, Link2) VALUES
    (1,  15  , 48  ), 
    (2,  48  , 15  ), 
    (3,  1   , NULL), 
    (4,  NULL, 5   ), 
    (5,  12  , 51  );

-- =================================================================

WITH 
    cte AS (
        SELECT 
            td.Id, td.Link1, td.Link2,
            RN = ROW_NUMBER() OVER (PARTITION BY IIF(td.Link1 <= td.Link2, td.Link1, td.Link2), IIF(td.Link1 > td.Link2, td.Link2, td.Link1) ORDER BY (SELECT NULL))
        FROM
            #TestData td
        )
SELECT 
    c.Id, c.Link1, c.Link2
FROM
    cte c
WHERE 
    c.RN = 1;

答案 2 :(得分:1)

您可以尝试沿着这条线(未经测试)

SELECT
  *
FROM
  (
    SELECT
      CASE
          WHEN Table1_LinkedId_1 >= Table1_LinkedId_2 THEN Table1_LinkedId_1
          ELSE Table1_LinkedId_2
      END AS Max,
      CASE
        WHEN Table1_LinkedId_1 <= Table1_LinkedId_2 THEN Table1_LinkedId_1
        ELSE Table1_LinkedId_2
      END AS Min
    FROM
      Figure1
  ) as Inner
GROUP BY
  Max,
  Min