我将您的意图解释为仅保留具有两行符合您已经尝试过的查询的日期组。如果您的问题是关于满足条件的行对,那么这种方法不是您需要的。
根据您的金额范围,您可以使用比例因子将 id 和金额组合成一个值:
select created_dt, min(id), max(id), max(amount)
from TEST
group by created_dt
having
count(*) = 2 and min(amount) = 0 and max(amount) > 0
and min(10000 * id + amount) = min(10000 * id)
同样,您可以尝试这个(作为最终条件的替代品),尽管它可能会导致溢出而不加小心。这个想法应该仍然是合理的:
and max(id) * max(amount) = max(id * amount)
另一种可能的聪明方法:
and min(id) = max(case when amount = 0 then id else -id end)
或者可能是最安全和最简单的,这两个选项之一:
and min(id) + min(amount) = min(id + amount)
and max(id) + max(amount) = max(id + amount)
那么完整的查询是:
select created_dt, min(id), max(id), max(amount)
from TEST
group by created_dt
having
count(*) = 2 and min(amount) = 0 and max(amount) > 0
and min(id) + min(amount) = min(id + amount)
编辑: 将所有数据放在一行中可能确实是一种优势,但我意识到您可能希望将其保留在两行中。如果您只是返回这些值而不是其他列,则仍然很容易得到它。
请注意,如果需要,您仍然可以将 ID 与连接一起使用以获取它们。
with data as (
select
created_dt,
min(id) as min_id, max(id) as max_id, max(amount) as max_amount
from TEST
group by created_dt
having
count(*) = 2 and min(amount) = 0 and max(amount) > 0
and min(id) + min(amount) = min(id + amount)
)
select split.*
from data cross apply (
values
(created_dt, min_id, 0),
(created_dt, max_id, max_amount)
) split(created_dt, id, amount)
此查询可以在没有 with、cross apply 和 values 的情况下编写,如果这些不是您可以随意使用的工具的话。