Sql 合并联合结果
我有下面的SQL查询Sql 合并联合结果,sql,sql-server,tsql,union,Sql,Sql Server,Tsql,Union,我有下面的SQL查询 select Count(emailID) as ViewsThatMonth, Day(entry_date) as day, Month(entry_date) as month, Year(entry_date) as year from email_views where emailID = 110197 Group By Day(entry_date), Month(entry_dat
select Count(emailID) as ViewsThatMonth,
Day(entry_date) as day,
Month(entry_date) as month,
Year(entry_date) as year
from email_views
where emailID = 110197
Group By Day(entry_date), Month(entry_date), Year(entry_date)
UNION ALL
select Count(emailID) as ViewsThatMonth,
Day(Record_Entry) as day,
Month(Record_Entry) as month,
Year(Record_Entry) as year
from dbo.tblOnlineEmail_Views
where emailID = 110197
Group By Day(Record_Entry), Month(Record_Entry), Year(Record_Entry)
order by 4, 3, 2
结果如下所示。我需要把同一天的结果合并起来。即,2010年8月23日的总数应为800
ViewsThatMonth day month year
---------------------------------
799 23 8 2010
1 23 8 2010
281 24 8 2010
88 25 8 2010
1 25 8 2010
基本上最简单的方法是将您的union设置为派生表或CTE,然后按日期对它们进行分组 即
将联合代码保持在最低限度:
select Count(emailID) as ViewsThatMonth,
Day(sort_date) as day,
Month(sort_date) as month,
Year(sort_date) as year
from (select v.*,
case c.caseid when 1 then entry_date else record_entry end sort_date
from email_views v
cross join (select 1 caseid union all select 2 caseid) c
where v.emailID = 110197) sq
Group By Day(sort_date), Month(sort_date), Year(sort_date)
编辑:将别名添加到子查询中您只需按一次分组:
SELECT Count(emailID) as ViewsThatMonth,
Day(entry_date) as day,
Month(entry_date) as month,
Year(entry_date) as year
from(
select emailID, Record_Entry AS entry_date
from email_views
where emailID = 110197
UNION ALL
select emailID, entry_date
from dbo.tblOnlineEmail_Views
where emailID = 110197
) AS t
Group By Day(entry_date), Month(entry_date), Year(entry_date)
order by 4, 3, 2
Count(Record\u Entry)
应该是Count(emailId)
我想。谢谢,但是我得到了一个“关键字'Group'附近语法不正确”的错误
SELECT Count(emailID) as ViewsThatMonth,
Day(entry_date) as day,
Month(entry_date) as month,
Year(entry_date) as year
from(
select emailID, Record_Entry AS entry_date
from email_views
where emailID = 110197
UNION ALL
select emailID, entry_date
from dbo.tblOnlineEmail_Views
where emailID = 110197
) AS t
Group By Day(entry_date), Month(entry_date), Year(entry_date)
order by 4, 3, 2