我有一个查询产生如下结果:
Company Member Account Date Check-ins
================================================================
Acme, Inc. Amanda Smith 4145886 7/3/2014 1
Acme, Inc. Amanda Smith 4145886 7/9/2014 1
Acme, Inc. Amanda Smith 4145886 7/23/2014 1
Acme, Inc. Gladys Jones 800138618 7/5/2014 1
Acme, Inc. Joe Ortega 800123972 7/15/2014 1
Acme, Inc. Joe Ortega 800123972 7/29/2014 1
以下是查询:
Select
com.CompanyName as [Company],
p.FirstName + ' ' + p.LastName as [Member],
a.AccountID as [Account],
CAST(mc.CheckInDate AS Date) [Date],
count(*) AS [Check-ins]
from
gym.Person p
join
gym.AccountPeople ap on p.PersonID = ap.PersonID
join
gym.Account a on a.AccountID = ap.AccountID
join
gym.MembershipStatus ms on a.MembershipStatusID = ms.MembershipStatusID
join
gym.Company com on a.CompanyID = com.CompanyID
join
gym.MemberCheckin mc on mc.PersonID = p.PersonID
where
mc.CheckInDate > '2014-7-1'
and mc.CheckInDate < DATEADD(dd, 1, CAST('2014-7-31' AS Date))
GROUP BY
com.CompanyName, a.AccountID,
p.FirstName + ' ' + p.LastName, CAST(mc.CheckInDate AS Date)
order by
com.CompanyName, p.FirstName + ' ' + p.LastName
我对如何以不同的方式解决这个问题感到困惑。请注意Amanda在7月,3日,9日和23日进行了3次检查。我需要结果显示每月每天的登记入住时间。因此,取代“日期”列,我需要31列(对于最长可能月份的每一天),如下所示:
1 2 3 4 5 6 7 8 9 10 .....
==============================================
0 0 1 0 0 0 0 0 1 0 ......
注意7月3日和7月9日3和9下的“办理登机手续”计数。如何构建查询以生成类似的结果?
答案 0 :(得分:1)
丑陋的答案......但你应该能够创建31个案例陈述来使其发挥作用。在你的选择(最后的作品)包括:
sum(case when day([date]) = 1 then 1 else 0 end) as day1,
sum(case when day([date]) = 2 then 1 else 0 end) as day2,
sum(case when day([date]) = 3 then 1 else 0 end) as day3,
sum(case when day([date]) = 4 then 1 else 0 end) as day4,
etc
sum(case when day([date]) = 31 then 1 else 0 end) as day31
如果有更好的答案会很好奇,但它应该适合你。它们是sum列,因此现有的group by应该可以正常运行。