Friday, February 24, 2012

Complex counting, joining and grouping

I have a sales stats table and I want to do some counting and grouping by
source and cluster (join required).
The 2 tables and sample data are as follows:
CREATE TABLE
dbo.stat (id_source varchar(10) not null,
id_period int not null,
id_dept varchar(10) not null,
ind_Domestic char(1) not null,
trade_count int not null)
CREATE TABLE dbo.stat_Hierarchy(id_dept varchar(5) not null,
id_cluster varchar(10) not null)
INSERT INTO stat VALUES('INTERNET',200601,'N41','Y',250)
INSERT INTO stat VALUES('INTERNET',200601,'N41','N',100)
INSERT INTO stat VALUES('INTERNET',200601,'S51','Y',200)
INSERT INTO stat VALUES('INTERNET',200601,'S51','N',120)
INSERT INTO stat VALUES('INTERNET',200601,'021','Y',50)
INSERT INTO stat VALUES('INTERNET',200601,'021','N',70)
INSERT INTO stat VALUES('INTERNET',200601,'131','Y',30)
INSERT INTO stat VALUES('INTERNET',200601,'131','N',70)
INSERT INTO stat VALUES('STORE',200601,'00P','Y',130)
INSERT INTO stat VALUES('STORE',200601,'00P','N',1)
INSERT INTO stat VALUES('STORE',200601,'00S','N',100)
INSERT INTO stat VALUES('STORE',200601,'N41','Y',130)
INSERT INTO stat VALUES('STORE',200601,'N41','N',250)
INSERT INTO stat VALUES('STORE',200601,'S51','Y',110)
INSERT INTO stat VALUES('STORE',200601,'S51','N',320)
INSERT INTO stat VALUES('STORE',200601,'021','Y',30)
INSERT INTO stat VALUES('STORE',200601,'021','N',40)
INSERT INTO stat VALUES('AGENCY',200601,'0101','Y',50)
INSERT INTO stat VALUES('AGENCY',200601,'0101','N',10)
INSERT INTO stat VALUES('AGENCY',200601,'0100300','Y',100
)
INSERT INTO stat VALUES('AGENCY',200601,'0100300','N',320
)
INSERT INTO stat VALUES('AGENCY',200601,'021','Y',150)
INSERT INTO stat VALUES('AGENCY',200601,'021','N',50)
INSERT INTO stat VALUES('AGENCY',200601,'131','Y',20)
INSERT INTO stat VALUES('AGENCY',200601,'131','N',80)
INSERT INTO stat_Hierarchy VALUES('00P','IB_CL_OTHE')
INSERT INTO stat_Hierarchy VALUES('00S','IB_CL_OTHE')
INSERT INTO stat_Hierarchy VALUES('0101','LV_CL_SALE')
INSERT INTO stat_Hierarchy VALUES('021','LV_CL_SALE')
INSERT INTO stat_Hierarchy VALUES('131','LV_CL_SALE')
INSERT INTO stat_Hierarchy VALUES('0100300','HV_CL_SALE')
INSERT INTO stat_Hierarchy VALUES('N41','HV_CL_SALE')
INSERT INTO stat_Hierarchy VALUES('S51','HV_CL_SALE')
And I want the data to be returned like so:
id_cluster,id_source,ind_Domestic,trade_
count
HV_CL_SALE,INTERNET,N,220
HV_CL_SALE,INTERNET,Y,450
HV_CL_SALE,STORE,N,570
HV_CL_SALE,STORE,Y,240
IB_CL_OTHE,STORE,N,101
IB_CL_OTHE,STORE,Y,130
LV_CL_SALE,AGENCY,N,140
LV_CL_SALE,AGENCY,Y,200
LV_CL_SALE,INTERNET,N,140
LV_CL_SALE,INTERNET,Y,80
LV_CL_SALE,STORE,N,40
LV_CL_SALE,STORE,Y,30
How could I do this?select
h.id_cluster,
s.id_source,
s.ind_Domestic,
sum(s.trade_count) as trade_count
from stat s
inner join stat_Hierarchy h on h.id_dept=s.id_dept
group by h.id_cluster,s.id_source,s.ind_Domestic
order by h.id_cluster,s.id_source,s.ind_Domestic

No comments:

Post a Comment