sql server - Generate an excel like report from SQL -
i novice sql , have 2 tables ticket , ticketattributes following schema
create table [dbo].[ticket]( [ticketid] [int] identity(1,1) not null, --primary key [category] [varchar](256) not null, [description] [varchar](256) null, [libid] [int] not null, [status] [smallint] null, [logid] [int] null) ticket attributes
create table [dbo].[ticketattributes]( [ticketid] [int] not null, [ticketattrid] [int] identity(1,1) not null, [attributeid] [int] not null, [attributegroup] [varchar](255) null, [attributevalue] [nvarchar](max) null, [status] [smallint] null, [logid] [int] null) where ticket attribute table stores different attributes of ticket ticketstatus, ticketcategory etc.. need generate report looks like
ticketstatus1 ticketstatus 2 ticketstatus3 ----------------------------------------------------------------- ticketcategory1 7 3 ticketcategory2 4 ticketcategory3 8 i want see count of each of status of each ticket category. eg:- have following data in tickettable
---------------------------------------------- ticketid name price date ------------------------------------------------ 155 ticket4 $20 16 jan 2016 157 ticket3 $300 17 jan 2016 158 ticket1 $100 18 jan 2016 159 ticket2 $500 19 jan 2016 now in ticketattribute table
---------------------------------------------- ticketid attributeid attributevalue ------------------------------------------------ 155 500 joe 155 600 reserved 155 700 economy 155 800 san jose where attributeids
500=nameofthe passenger 600= status of ticket 700= class 800= destination now lets want see count of number of active tickets in each of class per status
booked cancelled paymentpending ............ ----------------------------------------------------------------- economy 7 3 economy plus 4 business 8 hope clear now. how go using sql query
using pivot
;with cte ( select c.attributevalue class ,s.attributevalue statusofticket ticket t left join ticketattributes c on t.ticketid = c.ticketid , c.attributeid = 700 left join ticketattributes s on t.ticketid = s.ticketid , s.attributeid = 600 ) select * cte pivot ( count(statusofticket) statusofticket in (reserved,cancelled,paymentpending) ) p using conditional aggregation:
select c.attributevalue class ,count(distinct case when s.attributevalue = 'reserved' c.ticketid end) reserved ,count(distinct case when s.attributevalue = 'cancelled' c.ticketid end) cancelled ,count(distinct case when s.attributevalue = 'paymentpending' c.ticketid end) paymentpending ticket t left join ticketattributes c on t.ticketid = c.ticketid , c.attributeid = 700 left join ticketattributes s on t.ticketid = s.ticketid , s.attributeid = 600 group c.attributevalue
Comments
Post a Comment