假设我的数据库数据结构是那样的
ShopId Transaction
001 1.000
001 2.000
001 3.000
002 1.000
002 2.000
002 3.000
现在可能有一些交易丢失了,假设
002 4.000
002 6.000
在上表中,缺少表的5.000事务。
我想编写一个查询,在我的数据库中找到上面缺少的序列号。
所以我的查询将返回结果
shopid transaction
002 5.000
答案 0 :(得分:2)
获取每ShopId
个缺失交易的数量:
SELECT ShopId
, count(*)
- max([Transaction])
+ min([Transaction])
- 1 as MissingTranCount
FROM yourtable
GROUP BY ShopId
获取遗失的交易:
2.Generate #shops:
SELECT ShopId as id
into #shops
FROM yourtable
GROUP BY ShopId
HAVING count(*)
- max([Transaction])
+ min([Transaction])
- 1 > 0
3.获取遗失的交易:
SELECT id
, number
FROM #numbers
cross join #shops shops
WHERE exists (SELECT 1
FROM yourtable
WHERE ShopId = id
and number < [Transaction]
)
and exists (SELECT 1
FROM yourtable
WHERE ShopId = id
and number > [Transaction]
)
and not exists (SELECT 1
FROM yourtable
WHERE ShopId = id
and number = [Transaction]
)