看下表:
时间 原料 数量
20140102 手套 20
20140102 围巾 10
20140102 袜子 30
20140103 手套 20
20140103 围巾 30
20140104 手套 10
20140104 袜子 10
... ... ...
需要得到的结果为:
时间 原料 数量 合计
20140102 手套 20 60
20140102 围巾 10
20140102 袜子 30
20140103 手套 20 50
20140103 围巾 30
20140104 手套 10 20
20140104 袜子 10
... ... ... ...
就是统计 每天 原料使用数量的总和 并显示在当天时间的第一行
------解决方案--------------------
试试这个:
--drop table tb
create table tb( 时间 varchar(10),原料 varchar(10),数量 int)
insert into tb
select '20140102', '手套', 20 union all
select '20140102', '围巾', 10 union all
select '20140102', '袜子', 30 union all
select '20140103', '手套', 20 union all
select '20140103', '围巾', 30 union all
select '20140104', '手套', 10 union all
select '20140104', '袜子', 10
go
select 时间,原料,数量,
case when rownum = 1 then cc else null end as 合计
from
(
select *,
ROW_NUMBER() over(partition by 时间 order by getdate()) rownum,
sum(数量) over(partition by 时间) cc
from tb
)t
/*
时间 原料 数量 合计
20140102 手套 20 60
20140102 围巾 10 NULL
20140102 袜子 30 NULL
20140103 手套 20 50
20140103 围巾 30 NULL
20140104 手套 10 20
20140104 袜子 10 NULL
*/
------解决方案--------------------
SELECT MAX(时间) AS Expr3, MAX(原料) AS Expr1, SUM(数量) AS Expr2
FROM yuanliao
GROUP BY 时间, 原料
ORDER BY 时间, 原料
统计不到时当天的合计
------解决方案--------------------
select 时间,原料,数量, case when rownum=1 then 合计 else null end 合计
from ( select *,ROW_NUMBER() over(partition by 时间 order by getdate()) as rownum,SUM(数量) over(partition by 时间) as 合计 from tb
) t
Over子句的一个优点是能够在返回基本列的同时,在同一行对它们进行聚合,也可以在表达式中混合使用
------解决方案--------------------