从非序列号中查找缺失的数字

时间:2013-09-18 04:11:45

标签: sql sql-server vb.net

我有一个包含5列(A1,A2,A3,A4,A5)的数据库,可存储5个数字。

这5个数字是"1,2,3,4,5"

A1     A2     A3     A4     A5
-------------------------------
2      4      5      Null  Null

我想得到缺少的数字,即“1”和“3”。 如何从5个数字中找到丢失的数字?

4 个答案:

答案 0 :(得分:2)

Select Replace(Replace(Replace(Replace(
Replace('12345',(Cast(Coalesce(A5,0) as varchar(1))),''),
(Cast(Coalesce(A4,0) as varchar(1))),''),
(Cast(Coalesce(A3,0) as varchar(1))),''),
(Cast(Coalesce(A2,0) as varchar(1))),''),
(Cast(Coalesce(A1,0) as varchar(1))),'') from Table1

Sql Fiddle Demo

答案 1 :(得分:2)

你可以这样做

WITH sequence AS
(
  SELECT 1 n UNION ALL
  SELECT n + 1 FROM sequence WHERE n < 5
)
SELECT n
  FROM sequence s LEFT JOIN table1 t
    ON s.n IN (t.a1, t.a2, t.a3, t.a4, t.a5)
 WHERE t.a1 IS NULL

输出:

| N |
|---|
| 1 |
| 3 |

这是 SQLFiddle 演示

答案 2 :(得分:1)

根据所需的输出,这可能有效。这将返回每行的相关缺失数字。

    SELECT CASE WHEN COALESCE(A1,0)<>1 AND COALESCE(A2,0)<>1 AND COALESCE(A3,0)<>1 
            AND COALESCE(A4,0)<>1 AND COALESCE(A5,0)<>1 THEN 1 ELSE '' END A
        , CASE WHEN COALESCE(A1,0)<>2 AND COALESCE(A2,0)<>2 AND COALESCE(A3,0)<>2 
            AND COALESCE(A4,0)<>2 AND COALESCE(A5,0)<>2 THEN 2 ELSE '' END B
        , CASE WHEN COALESCE(A1,0)<>3 AND COALESCE(A2,0)<>3 AND COALESCE(A3,0)<>3 
            AND COALESCE(A4,0)<>3 AND COALESCE(A5,0)<>3 THEN 3 ELSE '' END C
        , CASE WHEN COALESCE(A1,0)<>4 AND COALESCE(A2,0)<>4 AND COALESCE(A3,0)<>4 
            AND COALESCE(A4,0)<>4 AND COALESCE(A5,0)<>4 THEN 4 ELSE '' END D
        , CASE WHEN COALESCE(A1,0)<>5 AND COALESCE(A2,0)<>5 AND COALESCE(A3,0)<>5 
            AND COALESCE(A4,0)<>5 AND COALESCE(A5,0)<>5 THEN 5 ELSE '' END E
    FROM NumTest 
    WHERE COALESCE(A1,0)+COALESCE(A2,0)+COALESCE(A3,0)+COALESCE(A4,0)+COALESCE(A5,0)<>15

结果如下:

enter image description here

答案 3 :(得分:0)

你需要一个从1到(在这种情况下)5的整数表:

DECLARE @ints table (n int);
INSERT @ints VALUES (1), (2), (3), (4), (5);

第二,我们将表格行中的数字放入一个可比较的集合中:

SELECT x INTO #all FROM (
    SELECT A1 as x FROM myTable WHERE ID = myRow
    UNION ALL
    SELECT A2 as x FROM myTable WHERE ID = myRow
    UNION ALL
    SELECT A3 as x FROM myTable WHERE ID = myRow
    UNION ALL
    SELECT A4 as x FROM myTable WHERE ID = myRow
    UNION ALL
    SELECT A5 as x FROM myTable WHERE ID = myRow
    ) y

然后你可以得出答案:

SELECT @ints.n
FROM @ints left join #all on @ints.n = #all.x
WHERE #all.x is null
ORDER BY 1