我有一个表名“Numerator”有3列:No_Fact,Numerat和Date。像这样:
No_Fact Numerat Date
1207020015 000713 2012-07-02 00:00:00.000
1207020016 000720 2012-07-02 00:00:00.000
1207020017 000722 2012-07-02 00:00:00.000
1207020019 000723 2012-07-02 00:00:00.000
1207020022 000724 2012-07-02 00:00:00.000
1207020021 000733 2012-07-02 00:00:00.000
1207020020 000734 2012-07-02 00:00:00.000
1207020018 000735 2012-07-02 00:00:00.000
1208120001 000766 2012-08-12 00:00:00.000
1208120002 000769 2012-08-12 00:00:00.000
1208230001 000777 2012-08-23 00:00:00.000
1208230002 000780 2012-08-23 00:00:00.000
我想查看Numerat列中数字之间的一些缺失数字,所以我尝试使用以下代码:
SELECT A.Numerat+1 AS 'MISSING FROM', MIN(B.Numerat)-1 AS 'TO'
FROM Numerator A, Numerator B
WHERE A.Numerat < B.Numerat
GROUP BY A.Numerat
HAVING A.Numerat+1 < MIN(B.Numerat)
ORDER BY 1
结果集:
MISSING FROM TO
714 719
721 721
725 732
736 765
767 768
770 776
778 779
这是一个很好的代码。 但序列号太多,与简洁的需要不相容。所以我今天只想显示部分行(2012-08-23),喜欢这个:
MISSING FROM TO
778 779
我非常感谢能解码它的人,谢谢。
当表中插入的下一行时,有一件有趣的事情, 我的演出于2012年8月23日开始:
No_Fact Numerat Date
1208230001 000777 2012-08-23 00:00:00.000
1208230002 000780 2012-08-23 00:00:00.000
1208250001 000782 2012-08-25 00:00:00.000
1208250002 000783 2012-08-25 00:00:00.000
1208250003 000784 2012-08-25 00:00:00.000
1208250004 000785 2012-08-25 00:00:00.000
1208250005 000786 2012-08-25 00:00:00.000
1208250006 000788 2012-08-25 00:00:00.000
1208250007 000789 2012-08-25 00:00:00.000
1208250008 000790 2012-08-25 00:00:00.000
1208250009 000793 2012-08-25 00:00:00.000
1208250010 000794 2012-08-25 00:00:00.000
作为我最初的目的,我希望在Numerat专栏中看到缺少的数字,并且简单地说我只想展示我今天进入的一行,然后根据bluefeet的建议我使用以下代码:
SELECT A.Numerat+1 AS 'MISSING FROM', MIN(B.Numerat)-1 AS 'TO'
FROM Numerator A
INNER JOIN Numerator B
ON A.Numerat < B.Numerat
AND a.Tanggal = DATEADD(DAY, DATEDIFF(DAY, 0, GetDate()), 0)
GROUP BY A.Numerat
HAVING A.Numerat+1 < MIN(B.Numerat)
ORDER BY 1
并取得成果:
MISSING FROM TO
787 787
791 792
如果我们仔细查看,则会显示缺少的数字,即:
MISSING FROM TO
781 781
但是我们确切地知道,包括约会在内吗?是23或25.在这种情况下,确切地知道这个缺失的数字的日期,显然有一个缺失的数字,应该注意到,并且在所有公共假期的24日到期,让我们输入它并不重要25日。有人可以帮忙吗?
答案 0 :(得分:1)
以下是执行此查询的几种不同方法,所有方法都将日期合并到其中:
SELECT A.Numerat+1 AS 'MISSING FROM', MIN(B.Numerat)-1 AS 'TO'
FROM test A
INNER JOIN test B
ON A.Numerat < B.Numerat
AND a.dt = DATEADD(DAY, DATEDIFF(DAY, 0, GetDate()), 0)
GROUP BY A.Numerat
HAVING A.Numerat+1 < MIN(B.Numerat)
ORDER BY 1
或者
;with cte as
(
select numerat, dt,
row_number() over(partition by dt order by numerat) rn
from test
where dt = DATEADD(DAY, DATEDIFF(DAY, 0, GetDate()), 0)
)
select c.Numerat+1 MissingFrom, t.Numerat-1 [To]
from cte c
inner join test t
on c.Numerat < t.Numerat
where c.rn = 1
或者您可以使用没有日期的MAX()
聚合:
SELECT max([Missing From]), max([to])
FROM
(
SELECT A.Numerat+1 AS 'MISSING FROM', MIN(B.Numerat)-1 AS 'TO'
FROM test A
INNER JOIN test B
ON A.Numerat < B.Numerat
GROUP BY A.Numerat
HAVING A.Numerat+1 < MIN(B.Numerat)
) x