日期:2014-05-17  浏览次数:20408 次

求教统计函数rollup,cube
原数据
A B C D
DINNER 1 Day1 75.00
LUNCH 1 Day1 71.50
DINNER 2 Day1 76.75
LUNCH 2 Day1 196.92
LUNCH 2 Day2 0.00
LUNCH 2 Day5 0.00
DINNER 3 Day1 42.52
LUNCH 3 Day1 38.00
LUNCH 3 Day3 0.00
LUNCH 3 Day4 0.00
LUNCH 3 Day6 0.00
LUNCH 3 Day7 0.00
结果
DAILY 1 Day1 146.50
DAILY 2 Day1 273.67
DAILY 3 Day1 80.52
DAILY 2 Day2 0.00
DAILY 3 Day3 0.00
DAILY 3 Day4 0.00
DAILY 2 Day5 0.00
DAILY 3 Day6 0.00
DAILY 3 Day7 0.00
就是根据B和C sum(D) 再把这列名字换为'DAILY'
就叫

------解决方案--------------------
SQL code
if object_id('[TB]') is not null drop table [TB]
go
create table [TB] (A nvarchar(12),B int,C nvarchar(8),D numeric(5,2))
insert into [TB]
select 'DINNER',1,'Day1',75.00 union all
select 'LUNCH',1,'Day1',71.50 union all
select 'DINNER',2,'Day1',76.75 union all
select 'LUNCH',2,'Day1',196.92 union all
select 'LUNCH',2,'Day2',0.00 union all
select 'LUNCH',2,'Day5',0.00 union all
select 'DINNER',3,'Day1',42.52 union all
select 'LUNCH',3,'Day1',38.00 union all
select 'LUNCH',3,'Day3',0.00 union all
select 'LUNCH',3,'Day4',0.00 union all
select 'LUNCH',3,'Day6',0.00 union all
select 'LUNCH',3,'Day7',0.00

select * from [TB]


SELECT 'DAILY' AS A,B,C,SUM(D) AS D
FROM dbo.TB
GROUP BY B,C
ORDER BY B,C


/*
A    B    C    D
DAILY    1    Day1    146.50
DAILY    2    Day1    273.67
DAILY    2    Day2    0.00
DAILY    2    Day5    0.00
DAILY    3    Day1    80.52
DAILY    3    Day3    0.00
DAILY    3    Day4    0.00
DAILY    3    Day6    0.00
DAILY    3    Day7    0.00*/