我在SQL Server中有一个摘要表,其中包含我的日常生产详细信息,如下所示。
表名:ProductionDet
结构:
id int (primary key, auto increment)
date date
tran_type varchar(1) (this field has 'I' for Issue, 'R' for Receive.)
emp_id int
Proc_id int
Pcs int
weight decimal(10,3)
当某个员工进行一些生产时,我的应用程序会插入或更新该pcs,在该表中为该日期加权。此表具有唯一键,包含date,tran_type,emp_id和Proc_id。
现在我想基于此表创建包含打开和关闭详细信息的数据透视报表。此报告将生成各种类型的分组选项。例如每月,每日,每季度,每年,员工明智,流程明智。我们必须根据选定的日期计算开盘价和收盘价。 这是样本输出:
结果1(每日报告):
emp_id_1
________________________________________
Opening Receive Issued Closing
----------------------------------------
01/04/13 Pcs 5 5 2 8
Wgt 5.2458 5.142 2.222 8.1658
----------------------------------------
02/04/13 Pcs 8 3 7 4
Wgt 8.1658 3.547 7.888 3.8248
结果2(月报):
emp_id_1
________________________________________
Opening Receive Issued Closing
----------------------------------------
Apr '13 Pcs 5 8 9 4
Wgt 5.2458 8.689 10.11 3.8248
我正在使用SQL Server 2008. SQL Server 2012/2013中是否有选项?感谢。
答案 0 :(得分:0)
这是我在类似报告中使用的解决方案,当我需要将摘要记录到交易日期之前,我希望我理解正确的问题。
步骤#1
按日期分组所有数据。如果您想要雇主等过滤器,请在此查询中添加。
select *,ReceivedPcs - IssuedPcs PcsDelta,ReceivedWgt - IssuedWgt WgtDelta, row_number() over (order by date) RowNo
into #ReportData1
from
(
select Date,
sum(case when tran_type = 'I' then pcs else 0 end) IssuedPcs,
sum(case when tran_type = 'R' then pcs else 0 end) ReceivedPcs,
sum(case when tran_type = 'I' then [weight] else 0 end) IssuedWgt,
sum(case when tran_type = 'I' then [weight] else 0 end) ReceivedWgt
from ProductionDet
group by date
) s
第2步 加入结果并使用一组用于“今天”值(a)和一组用于在今天之前加总所有增量。
select *,ReceivedPcs - IssuedPcs PcsDelta,ReceivedWgt - IssuedWgt WgtDelta, row_number() over (order by date) RowNo
into #ReportData1
from
(
select Date,
sum(case when tran_type = 'I' then pcs else 0 end) IssuedPcs,
sum(case when tran_type = 'R' then pcs else 0 end) ReceivedPcs,
sum(case when tran_type = 'I' then [weight] else 0 end) IssuedWgt,
sum(case when tran_type = 'I' then [weight] else 0 end) ReceivedWgt
from ProductionDet
group by date
) s
您有每日报告的数据。您可以为月度报告应用相同的逻辑,只需按
分组或以任何其他方式获得月份。select a.Date, a.IssuedPcs, a.ReceivedPcs,
a.IssuedWgt, a.ReceivedWgt,
a.WgtDelta, a.PcsDelta,
sum(isnull(s.WgtDelta,0)) OpeningWgt ,
sum(isnull(s.PcsDelta,0)) OpeningPcs
from #ReportData1 a
left outer join #ReportData1 s on s.Date < a.Date
group by a.Date, a.IssuedPcs, a.ReceivedPcs, a.IssuedWgt, a.ReceivedWgt, a.WgtDelta, a.PcsDelta
我相信格式化应该不是问题。
我认为在SQL 2012中有一种更简单的方法,因为有一个与Row_number具有相似语法的函数,但我将解释如何做到这一点,以及该功能。