当没有行存在时,查询需要返回行

时间:2016-05-25 17:06:38

标签: sql sql-server sql-server-2012

我有一个sql查询(下面),当表中不存在今天的日期时,该查询不起作用。如何强制它返回除日期字段中除今天日期之外没有值的空白行?这是一年多的回顾,但关键是看今天的日期。

select p.*
from [Apprise].[dbo].[adadjusttotal] c
--- Match
join (select distinct  a.adjustdate as curr_dte, max(b.adjustdate) over (partition by a.adjustdate) as prev_dte 
from [Apprise].[dbo].[adadjusttotal] a
join [Apprise].[dbo].[adadjusttotal] b  on year(a.adjustdate) -1 >= year(b.adjustdate) 
and month(a.adjustdate) >= month(b.adjustdate) 
and day(a.adjustdate) >=  day(b.adjustdate)
where a.adjustdate > getdate() -5 ) x
on c.adjustdate  = x.curr_dte
--- Prev Year
join [Apprise].[dbo].[adadjusttotal] p
on  p.adjustdate  = x.prev_dte               
where cast(c.adjustdate as date) = cast(getdate() as date)
and p.adjusttype = 'QuarterByDate'

2 个答案:

答案 0 :(得分:0)

在查询后添加:

if @@rowcount=0 
    select cast(getdate() as datetime),Null as col1,null as col2

if @@rowcount=0

    select convert(varchar(12), getdate(),101) as curdate, null as col1,null as col2

答案 1 :(得分:0)

你可以这样做:

select p.*
from
(select 1 as dummy) x
outer apply (
    select p.*
    from [Apprise].[dbo].[adadjusttotal] c
    --- Match
    join (select distinct  a.adjustdate as curr_dte, max(b.adjustdate) over (partition by a.adjustdate) as prev_dte 
    from [Apprise].[dbo].[adadjusttotal] a
    join [Apprise].[dbo].[adadjusttotal] b  on year(a.adjustdate) -1 >= year(b.adjustdate) 
    and month(a.adjustdate) >= month(b.adjustdate) 
    and day(a.adjustdate) >=  day(b.adjustdate)
    where a.adjustdate > getdate() -5 ) x
    on c.adjustdate  = x.curr_dte
    --- Prev Year
    join [Apprise].[dbo].[adadjusttotal] p
    on  p.adjustdate  = x.prev_dte               
    where cast(c.adjustdate as date) = cast(getdate() as date)
    and p.adjusttype = 'QuarterByDate'
) p

由于这个外部数据总是与1行连接,所以当数据实际上不存在时,它也应该返回完全空行。

当然,对于您需要添加的任何默认值,您必须在select子句中执行此操作。 select p.*只是为了让它更短,而且我不知道你的专栏是什么。