【发布时间】:2018-01-31 00:07:39
【问题描述】:
我有一个现有问题,我认为这会引导我回答,但现在我还有另一个问题,我不知道如何解决它。我原来的问题在这里:How to find Invoice detail counter column not in numeric order 在我的表中,当我运行查询时,我有以下信息
Select * from Invoice_detail where Description like 'Service%'
结果:
Detail_ID date_Created Invoice_id Description
1 1/1/18 12:02:03 1 Service 1
2 1/1/18 12:02:04 1 Service 2
3 1/1/18 12:02:05 1 Service 3
4 1/1/18 12:06:03 2 Service 1
5 1/1/18 12:06:04 2 Service 2
6 1/1/18 12:06:05 2 Service 3
7 1/1/18 12:08:03 3 Service 1
8 1/1/18 12:08:04 3 Service 2
9 1/1/18 12:08:05 3 Service 3
10 1/1/18 12:12:03 4 Service 1
12 1/1/18 12:12:05 4 Service 3
13 1/1/18 12:15:05 5 Service 1
15 1/1/18 12:15:05 5 Service 2
Select * from Invoice_Detail returns:
Detail_ID date_Created Invoice_id Description
1 1/1/18 12:02:03 1 Service 1
2 1/1/18 12:02:04 1 Service 2
3 1/1/18 12:02:05 1 Service 3
4 1/1/18 12:06:03 2 Service 1
5 1/1/18 12:06:04 2 Service 2
6 1/1/18 12:06:05 2 Service 3
7 1/1/18 12:08:03 3 Service 1
8 1/1/18 12:08:04 3 Service 2
9 1/1/18 12:08:05 3 Service 3
10 1/1/18 12:12:03 4 Service 1
12 1/1/18 12:12:05 4 Service 3
13 1/1/18 12:15:05 5 Service 1
14 1/1/18 12:15:05 5 Test
15 1/1/18 12:15:05 5 Service 2
我最初的问题 - 我正在运行的查询是:
select id.invoice_id
from invoice_detail id
where Description like ('Service%')
group by id.invoice_id
having count(*) <> max(id.detail_id) - min(id.detail_id) + 1;
在我之前的问题中回答的这个查询完全符合我的要求 - 但是,我发现了一些特殊情况,会弹出这个问题。
我只想返回invoice_ID 4 ONLY(上图)在这种情况下 - Detail_ID '11' 不存在并且可能已被删除。我不想看到 Invoice_id 5,因为 detail_id 存在,只是不是为了那张票。
我几乎认为我也需要这样的东西: SQL: find missing IDs in a table
【问题讨论】:
-
您的查询不就是这样吗?
-
我编辑了这个问题。我的查询将返回 4 和 5。注意“where”子句
-
不关注。 仅当 Detail_ID 11 不存在于表中时,才返回 invoice_ID 4。我不想看到 Invoice_id 5,因为 detail_id 存在,只是不适合那张票。
-
希望这样可以更清楚。
标签: sql sql-server sql-server-2008 sql-server-2012