【发布时间】:2021-01-25 07:12:44
【问题描述】:
Use ReportingDb
select hd.company_name as CompanyName,
COALESCE((select sum(case datepart(dw, hrd.created_datetime)
when 1 then 1 else 0
end) from dbo.HdSurvey_Result_Details hrd where hd.company_id = hrd.company_id and (hrd.created_datetime between '2019-10-10 10:46:19' AND '2020-10-10 10:46:19')),0) as Monday,
COALESCE((select sum(case datepart(dw,hrd.created_datetime)
when 2 then 1 else 0
end)from dbo.HdSurvey_Result_Details hrd where hd.company_id = hrd.company_id and (hrd.created_datetime between '2019-10-10 10:46:19' AND '2020-10-10 10:46:19')),0) as Tuesday,
COALESCE((select sum(case datepart(dw,hrd.created_datetime)
when 3 then 1 else 0
end)from dbo.HdSurvey_Result_Details hrd where hd.company_id = hrd.company_id and (hrd.created_datetime between '2019-10-10 10:46:19' AND '2020-10-10 10:46:19')),0) as Wednesday,
COALESCE((select sum(case datepart(dw,hrd.created_datetime)
when 4 then 1 else 0
end)from dbo.HdSurvey_Result_Details hrd where hd.company_id = hrd.company_id and (hrd.created_datetime between '2019-10-10 10:46:19' AND '2020-10-10 10:46:19')),0) as Thursday,
COALESCE((select sum(case datepart(dw,hrd.created_datetime)
when 5 then 1 else 0
end)from dbo.HdSurvey_Result_Details hrd where hd.company_id = hrd.company_id and(hrd.created_datetime between '2019-10-10 10:46:19' AND '2020-10-10 10:46:19')),0) as Friday,
COALESCE((select sum(case datepart(dw,hrd.created_datetime)
when 6 then 1 else 0
end)from dbo.HdSurvey_Result_Details hrd where hd.company_id = hrd.company_id and (hrd.created_datetime between '2019-10-10 10:46:19' AND '2020-10-10 10:46:19')),0) as Saturday,
COALESCE((select sum(case datepart(dw,hrd.created_datetime)
when 7 then 1 else 0
end)from dbo.HdSurvey_Result_Details hrd where hd.company_id = hrd.company_id and (hrd.created_datetime between '2019-10-10 10:46:19' AND '2020-10-10 10:46:19')),0) as Sunday,
COALESCE((select COUNT_BIG(*) from dbo.HdSurvey_Result_Details hrd where hd.company_id = hrd.company_id and(hrd.created_datetime between '2019-10-10 10:46:19' AND '2020-10-10 10:46:19')),0) as TotalResults
from HdSurvey_Result_Details as hd
group by hd.company_name,hd.company_id
【问题讨论】:
-
这取决于execution plan 知道如何更新。
标签: sql sql-server optimization query-performance