全部为零时排除多个和行

时间:2014-11-06 18:36:37

标签: sql sql-server database

如果所有3个sum列都为零,我想在查询结果中排除一行。

Select Name
,sum(case when cast(Date as date) <= Convert(datetime, '2014-05-01') then 1 else 0 end) as 'First'
,sum(case when cast(Date as date) <= Convert(datetime, '2014-04-01') then 1 else 0 end) as 'Second'
,sum(case when cast(Date as date) <= Convert(datetime, '2013-05-01') then 1 else 0 end) as 'Third'
FROM [dbo].[Posting]
inner join dbo.Names on Name.NameId = Posting.NameId
where active = 1 
group by Name
order by Name

4 个答案:

答案 0 :(得分:3)

这可能适合你:

select * from
( 
.......your query......
) as t
where First <> 0 or Second <> 0 or Third <> 0

答案 1 :(得分:1)

您可以重复having子句中的表达式:

having sum(case when cast(Date as date) <= Convert(datetime, '2014-05-01') then 1 else 0 end) > 0 or
       sum(case when cast(Date as date) <= Convert(datetime, '2014-04-01') then 1 else 0 end) > 0 or
       sum(case when cast(Date as date) <= Convert(datetime, '2013-05-01') then 1 else 0 end) > 0

但是,您可以更简单地将条件写为:

having sum(case when cast(Date as date) <= '2014-05-01' then 1 else 0 end) > 0 or
       sum(case when cast(Date as date) <= '2014-04-01' then 1 else 0 end) > 0 or
       sum(case when cast(Date as date) <= '2013-05-01' then 1 else 0 end) > 0

或者,因为第一个包含另外两个:

having sum(case when cast(Date as date) <= '2014-05-01' then 1 else 0 end) > 0

或者,更简单:

having min(date) <= '2014-05-01'

此外,您应该仅对字符串和日期名称使用单引号。不要对列别名使用单引号(它可能导致混淆和问题)。选择不需要转义的名称。如果你有一个麻烦的名字,那么使用方括号。

答案 2 :(得分:1)

您可以使用此查询:

with temp as 

(Select Name
,sum(case when cast(Date as date) <= Convert(datetime, '2014-05-01') then 1 else 0 end) as 'First'
,sum(case when cast(Date as date) <= Convert(datetime, '2014-04-01') then 1 else 0 end) as 'Second'
,sum(case when cast(Date as date) <= Convert(datetime, '2013-05-01') then 1 else 0 end) as 'Third'
FROM [dbo].[Posting]
inner join dbo.Names on Name.NameId = Posting.NameId
where active = 1 
group by Name
order by Name)

select * from temp where [first]+[second]+[third]=0

答案 3 :(得分:0)

您不需要Convert datedatetime

cast(Date as date)会将列日期值转换为yyyy-MM-dd格式

with CTE
as
(select 
sum(case when cast(Date as date) <=  '2014-05-01' then 1 else 0 end) as 'First'
,sum(case when cast(Date as date) <=  '2014-04-01' then 1 else 0 end) as 'Second'
,sum(case when cast(Date as date) <=  '2013-05-01' then 1 else 0 end) as 'Third' from myTable
)
where CTE.First=0 and CTE.Second=0 and CTE.Third=0