我想创建一个报告,显示日历类型布局中每个客户每周的会议数。我正在使用SQL Server Reporting Services 2005。
为简单起见,我们假设我们只有这两个表:
客户
预约
使用此布局生成报告的最有效方法是什么?
| WEEK #
CUSTOMER | 1| 2| 3| 4| 5| 6|...|52| TOTAL
---------+-+-+-+-+-+-+--+--+---+--+------
Cust A | 0| 2| 0| 1| 0| 0|...| 1| 4
Cust B | 0| 1| 0| 1| 1| 0|...| 0| 3
Cust C | 0| 0| 0| 1| 0| 0|...| 0| 1
Cust D | 1| 0| 0| 0| 1| 0|...| 0| 2
编辑:记住有些年份可能会从第53周开始。
答案 0 :(得分:1)
我跳过了所有52(53)周的枚举,并且只列举了我放置测试数据的那些。希望你明白了。
DECLARE @Customer TABLE
(
[Id] int not null primary key,
[Name] nvarchar(50) not null
);
DECLARE @Appointment TABLE
(
[Id] int not null primary key,
[CustomerId] int not null,
[OccurredOn] datetime not null DEFAULT getdate(),
[Subject] nvarchar(50) not null
);
INSERT INTO @Customer
SELECT 1, 'Aaron Burr' UNION ALL
SELECT 2, 'John Adams' UNION ALL
SELECT 3, 'George Washington';
INSERT INTO @Appointment
SELECT 1, 1, '2009-01-04', 'Ants in the pants' UNION ALL
SELECT 2, 1, '2009-02-04', 'Follow up' UNION ALL
SELECT 3, 1, '2009-07-20', 'Check-up' UNION ALL
SELECT 4, 2, '2009-02-05', 'Wellness Check' UNION ALL
SELECT 5, 2, '2009-11-26', 'Private' UNION ALL
SELECT 6, 2, '2009-06-03', 'Stubbed Toe' UNION ALL
SELECT 7, 3, '2009-11-27', 'Toothache' UNION ALL
SELECT 8, 3, '2009-11-28', 'Crown';
WITH AggregateAppointments AS
(
SELECT c.Id,
c.Name,
DATEPART(wk, a.OccurredOn) [Week],
COUNT(c.Id) [Count]
FROM @Appointment a
JOIN @Customer c ON a.CustomerId = c.Id
GROUP BY c.Id, c.Name, DATEPART(wk, a.OccurredOn)
),
PivotAppointments AS
(
SELECT [Id],
[Name],
ISNULL([53], 0) [53],
ISNULL([2], 0) [2],
ISNULL([6], 0) [6],
ISNULL([23], 0) [23],
ISNULL([30], 0) [30],
ISNULL([48], 0) [48]
FROM AggregateAppointments
PIVOT (
SUM([Count])
FOR [Week] IN ([2], [6], [23], [30], [48], [53])
) as [PivotAppointments]
)
SELECT *,
[53]+[2]+[6]+[23]+[30]+[48] [Total]
FROM PivotAppointments
结果:
[Id] [Name] [53] [2] [6] [23] [30] [48] [Total]
------------------------------------------------------------------
1 Aaron Burr 0 1 1 0 1 0 3
2 George Washington 0 0 0 0 0 2 2
3 John Adams 0 0 1 1 0 1 3