SQL Cube

Cube

use pubs
go

IF EXISTS (SELECT * FROM sysobjects WHERE name='automobile_sales_detail' and type='U')
	drop table automobile_sales_detail
go

create table automobile_sales_detail
(
rowid		int	not null identity ,
model		char(6)	not null ,
year		smallint	not null check (year between 1985 and 2000),
color		char(5)	not null,
style		char(8)	not null,
units_sold	int	not null
)
go

insert automobile_sales_detail values ('Chevy',1988,'Blue','Sedan',100)
insert automobile_sales_detail values ('Chevy',1989,'Green','Sedan',50)
insert automobile_sales_detail values ('Chevy',1990,'Blue','2-Door',25)
insert automobile_sales_detail values ('Acura',1995,'Black','Sedan',33)
insert automobile_sales_detail values ('Nissan',1992,'Red','SUV',96)
insert automobile_sales_detail values ('Nissan',1991,'Blue','SUV',43)
insert automobile_sales_detail values ('Acura',1993,'Black','2-Door',62)
insert automobile_sales_detail values ('Acura',1995,'Black','Sedan',78)
insert automobile_sales_detail values ('Nissan',1992,'Red','Sedan',33)
insert automobile_sales_detail values ('Chevy',1990,'Blue','Sedan',106)
insert automobile_sales_detail values ('Chevy',1988,'Blue','Sedan',100)
go

select * from automobile_sales_detail
go

select sum(units_sold),model,year,color,style 
from automobile_sales_detail
group by model,year,color,style
go

select sum(units_sold),model,year,color,style 
from automobile_sales_detail
group by model,year,color,style with cube
go

select sum(units_sold),model,year,color,style 
from automobile_sales_detail
group by model,year,color,style with rollup
go

IF EXISTS (SELECT * FROM sysobjects WHERE name='auto_cube' and type='V')
	drop view auto_cube
go

create view auto_cube (units, model, year, color, style) as
select sum(units_sold),isnull(model,'ALL'),isnull(convert(char(4),year),'ALL'),
isnull(color,'ALL'),isnull(style,'ALL')
from automobile_sales_detail
group by model,year,color,style with cube
go

select * from auto_cube
go

select * from auto_cube where model='Acura' and color='ALL'
and style='ALL' and year='1993'
go