使用COALESCE添加列名称

时间:2016-07-26 13:03:03

标签: sql sql-server coalesce

我有这个存储过程,我想为我得到的值添加一个列名。我在哪里添加

  

as“TotalNewspapers”

(或我必须添加的任何内容)如果我使用 COALESCE

SELECT COALESCE ((SELECT 
  count(distinct Appendage.AppendageName) as "TotalNewspapers" 
  FROM Edition
   inner join SourceInformation on (SourceInformation.SourceInformationID =  Edition.SourceInformationID)
   left join Appendage on (Appendage.AppendageID = Edition.AppendageID)
   inner join Pages on (Edition.EditionID = Pages.EditionID)
  where 
    Edition.publishdate >= DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0)
    and Edition.publishdate <= DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0)+1 
    and Pages.PullBy is null
    and Edition.FinishDate is null
group by Appendage.AppendageName, SourceInformation.SourceInformationName, Pages.PullBy, Edition.FinishDate, Appendage.AppendageID
having count(Pages.PullBy) > 1) , 0);

1 个答案:

答案 0 :(得分:2)

您可以使用ISNULLCOALESCE

SELECT ISNULL(( --OR COALESCE
    SELECT count(distinct a.AppendageName) as [TotalNewspapers]
    FROM Edition e
    inner join SourceInformation s
        on (s.SourceInformationID =  e.SourceInformationID)
    left join Appendage a
        on (a.AppendageID = e.AppendageID)
    inner join Pages p
        on (e.EditionID = p.EditionID)
    where 
        e.publishdate >= DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0)
        and e.publishdate <= DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0)+1 
        and p.PullBy is null
        and e.FinishDate is null
    group by a.AppendageName, s.SourceInformationName, p.PullBy, e.FinishDate, a.AppendageID
    having count(p.PullBy) > 1
),0) as [TotalNewspapers]

我删除了子查询,您只需要在一个select语句中完成所有操作。同时添加aliases