我创建了一个名为tbl_timesheet_hours的数据库表,如下所示:
timesheet_no
work_order_no
work_order_date
work_order_hours
表中填充的数据为:
timesheet_no work_order_no work_order_date work_order_hours
4 NTS0026B 2012-01-02 1
4 NTS0031B 2012-01-02 9
4 NTS0031B 2012-01-03 8
4 NTS0031B 2012-01-04 7
4 NTS0031B 2012-01-05 6
4 NTS0031B 2012-01-06 5
4 NTS0031B 2012-01-07 4
4 NTS0031B 2012-01-08 3
我需要创建一个查询,该查询将形成时间表报告的基础,该报告可以以典型的承包商的时间表格式打印,即,它将在第一列中显示work_order_no字段,然后为每个分配显示小时数天。我创建的查询是:
SELECT
work_order_no,
switch(Format(work_order_date,'ddd') = "Mon", SUM(work_order_hours)) AS [Mon],
switch(Format(work_order_date,'ddd') = "Tue", SUM(work_order_hours)) AS [Tue],
switch(Format(work_order_date,'ddd') = "Wed", SUM(work_order_hours)) AS [Wed],
switch(Format(work_order_date,'ddd') = "Thu", SUM(work_order_hours)) AS [Thu],
switch(Format(work_order_date,'ddd') = "Fri", SUM(work_order_hours)) AS [Fri],
switch(Format(work_order_date,'ddd') = "Sat", SUM(work_order_hours)) AS [Sat],
switch(Format(work_order_date,'ddd') = "Sun", SUM(work_order_hours)) AS [Sun]
FROM tbl_timesheet_hours
WHERE timesheet_no=4
GROUP BY work_order_date, work_order_no;
查询生成以下结果集
work_order_no Mon Tue Wed Thu Fri Sat Sun
NTS0026B 1
NTS0031B 9
NTS0031B 8
NTS0031B 7
NTS0031B 6
NTS0031B 5
NTS0031B 4
NTS0031B 3
是否可以重构查询以生成以下结果集?
work_order_no Mon Tue Wed Thu Fri Sat Sun
NTS0026B 1
NTS0031B 9 8 7 6 5 4 3
非常感谢任何类型的协助。感谢。
答案 0 :(得分:3)
您可以按如下方式使用交叉表查询:
TRANSFORM Sum(tbl_timesheet_hours.[work_order_hours]) AS SumOfwork_order_hours
SELECT tbl_timesheet_hours.[work_order_no], Sum(tbl_timesheet_hours.[work_order_hours]) AS [Total Of work_order_hours]
FROM tbl_timesheet_hours
GROUP BY tbl_timesheet_hours.[work_order_no]
ORDER BY Format([work_order_date],'ddd')
PIVOT Format([work_order_date],'ddd') In ("Mon","Tue","Wed","Thu","Fri","Sat","Sun");
答案 1 :(得分:0)
您是否尝试过使用 SWITCH
内的SUM()
表达式?像这样:
SELECT
work_order_no,
SUM(switch(Format(work_order_date,'ddd') = "Mon", work_order_hours)) AS [Mon],
SUM(switch(Format(work_order_date,'ddd') = "Tue", work_order_hours)) AS [Tue],
SUM(switch(Format(work_order_date,'ddd') = "Wed", work_order_hours)) AS [Wed],
SUM(switch(Format(work_order_date,'ddd') = "Thu", work_order_hours)) AS [Thu],
SUM(switch(Format(work_order_date,'ddd') = "Fri", work_order_hours)) AS [Fri],
SUM(switch(Format(work_order_date,'ddd') = "Sat", work_order_hours)) AS [Sat],
SUM(switch(Format(work_order_date,'ddd') = "Sun", work_order_hours)) AS [Sun]
FROM tbl_timesheet_hours
WHERE timesheet_no=4
GROUP BY work_order_no;
除此之外,还要从work_order_date
移除GROUP BY
。