GROUP BY HAVING逻辑无效(最小/最大日期)

时间:2019-03-22 16:09:01

标签: tsql ssms

我有2张桌子:苹果和橘子。苹果每个ApplesID都有一个FirstDate列和一个LastDate列。 Oranges仅有一个Date列,每个ApplesID具有多个记录(发生),每个记录可以具有不同的日期。从技术上讲,这两个都不提取,但逻辑是每个ApplesID的min(Oranges.Date)= Apples.FirstDate,而max(Oranges.Date)= Apples.LastDate。我只是在查询上述逻辑不正确的地方。

下面是我的查询试图找到它,但是当我运行它时,我看到上面的逻辑成立和不成立的结果。逻辑成立的结果不应在结果集中。我在做什么错了?

select distinct 
a.ApplesID
, convert(varchar(10), a.FirstDate, 103) as 'FirstDate'
, convert(varchar(10), a.LastDate, 103) as 'LastDate'
, min(convert(varchar(10), o.Date, 103)) as 'FirstDT'
, max(convert(varchar(10), o.Date, 103)) as 'LastDT'
from Apples a with(nolock)
join Oranges o with(nolock)
    on o.ApplesID = a.ApplesID
where (o.Date between '01/01/2018' and '02/28/2019' and a.FirstDate >= '01/01/2018')
    and a.ApplesID > 0
    and a.Deleted = 0
group by a.ApplesID, a.FirstDate, a.LastDate
having (min(o.Date) <> a.FirstDate or max(o.Date) <> a.LastDate)
order by a.ApplesID

1 个答案:

答案 0 :(得分:0)

您应该在HAVING上将其设为AND,而不是OR。或检查两个过滤条件中的任何一个...因此一个条件成立,另一个条件成立(或相反)。

select distinct 
a.ApplesID
, convert(varchar(10), a.FirstDate, 103) as 'FirstDate'
, convert(varchar(10), a.LastDate, 103) as 'LastDate'
, min(convert(varchar(10), o.Date, 103)) as 'FirstDT'
, max(convert(varchar(10), o.Date, 103)) as 'LastDT'
from Apples a with(nolock)
join Oranges o with(nolock)
    on o.ApplesID = a.ApplesID
where (o.Date between '01/01/2018' and '02/28/2019' and a.FirstDate >= '01/01/2018')
    and a.ApplesID > 0
    and a.Deleted = 0
group by a.ApplesID, a.FirstDate, a.LastDate
having ((min(o.Date) <> a.FirstDate) AND (max(o.Date) <> a.LastDate))
order by a.ApplesID