SQL Server is there a way around repeated conditional lines -
hello trying clean query , there 1 line repeated 6 times. there way set constant in sql?
here example of issue:
select distinct dsf.cityname, ( select count (distinct dsf1.incdtkey) dbo.incidentfile dsf1 dsf1.incidentmostsevere in ('1', '2', '4', '5', '6') , dsf1.categorykey in ('15', '01', '02', '03', '04', '05', '06')<----- , dsf1.cityname = dsf.cityname) 'weapons possession 11-12', ( select count (distinct dsf2.incdtkey) dbo.incidentfile dsf2 dsf2.incidentmostsevere in ('7', '8', '9', '10', '11', '12') , dsf2.categorykey in ('15', '01', '02', '03', '04', '05', '06') <----- , dsf2.cityname = dsf.cityname) 'drugs related 11-12', ( select count (distinct dsf3.incdtkey) dbo.incidentfile dsf3 dsf3.incidentmostsevere in ('14', '15', '17', '20', '21', '22', '26') , dsf3.categorykey in ('15', '01', '02', '03', '04', '05', '06') <----- , dsf3.cityname = dsf.cityname) 'incident injury 11-12', ( select count (distinct dsf4.incdtkey) dbo.incidentfile dsf4 dsf4.incidentmostsevere in ('16', '18', '19', '23', '24', '25') , dsf4.categorykey in ('15', '01', '02', '03', '04', '05', '06') <----- , dsf4.cityname = dsf.cityname) 'incident no injury 11-12', ( select count (distinct dsf5.incdtkey) dbo.incidentfile dsf5 dsf5.incidentmostsevere in ('3', '13', '29', '31', '32', '33') , dsf5.categorykey in ('15', '01', '02', '03', '04', '05', '06') <----- , dsf5.cityname = dsf.cityname) 'other reason 11-12', ( select count (distinct dsf6.incdtkey) dbo.incidentfile dsf6 dsf6.categorykey in ('15', '01', '02', '03', '04', '05', '06') <----- , dsf6.cityname = dsf.cityname) 'total incidents' dbo.incidentfile dsf group dsf.cityname order dsf.cityname
thanks
you should able use cte , aggregate function case
expression:
;with cte ( select distinct cityname, incidentmostsevere, incdtkey dbo.incidentfile categorykey in ('15', '01', '02', '03', '04', '05', '06') ) select cityname, count(case when incidentmostsevere in ('1', '2', '4', '5', '6') incdtkey end) 'weapons possession 11-12', count(case when incidentmostsevere in ('7', '8', '9', '10', '11', '12') incdtkey end) 'drugs related 11-12', count(case when incidentmostsevere in ('14', '15', '17', '20', '21', '22', '26') incdtkey end) 'incident injury 11-12', count(case when incidentmostsevere in ('16', '18', '19', '23', '24', '25') incdtkey end) 'incident no injury 11-12', count(case when incidentmostsevere in ('3', '13', '29', '31', '32', '33') incdtkey end) 'other reason 11-12', count(case when incidentmostsevere in ('15', '01', '02', '03', '04', '05', '06') incdtkey end) 'total incidents' cte group cityname order cityname
Comments
Post a Comment