SQL - how to consolidate Or statements - sql

There must be a better way to write the query below, if you have any suggestions please let me know.
SELECT *
FROM
[eSDR_Full].[dbo].[course_register]
WHERE
broad_field_code = '08'
AND narrow_field_code = '05'
AND detail_field_code = '05'
AND end_month is null
AND disabled <> 'Y'
OR broad_field_code = '08'
AND narrow_field_code = '05'
AND detail_field_code = '05'
AND end_month > '201512'
AND disabled <> 'Y'
OR broad_field_code = '08'
AND narrow_field_code = '05'
AND detail_field_code = '05'
AND end_month is null
AND disabled is null
OR broad_field_code = '08'
AND narrow_field_code = '05'
AND detail_field_code = '05'
AND end_month > '201512'
AND disabled is null
ORDER BY
end_month DESC

First refactoring:
SELECT *
FROM [eSDR_Full].[dbo].[course_register]
Where (broad_field_code = '08' and narrow_field_code = '05' and detail_field_code = '05')
and ( (end_month is null and disabled <> 'Y')
or (end_month > '201512' and disabled <> 'Y')
or (end_month is null and disabled is null)
or (end_month > '201512' and disabled is null))
order by end_month desc
This makes it clear that you have a common prefix to all the conditions.
Second refactoring takes advantage of other commonalities:
SELECT *
FROM [eSDR_Full].[dbo].[course_register]
Where (broad_field_code = '08' and narrow_field_code = '05' and detail_field_code = '05')
and (end_month is null or end_month > '201512')
and (disabled is null or disabled <> 'Y')
order by end_month desc
Now it's clear that we just have a series of stacked ANDs based on simple conditions of one column each, so we can do this:
SELECT *
FROM [eSDR_Full].[dbo].[course_register]
Where broad_field_code = '08'
and narrow_field_code = '05'
and detail_field_code = '05'
and coalesce(end_month, '999999') > '201512'
and coalesce(disabled, 'N') <> 'Y')
order by end_month desc

This should work:
SELECT *
FROM [eSDR_Full].[dbo].[course_register]
WHERE broad_field_code = '08'
AND narrow_field_code = '05'
AND detail_field_code = '05'
AND (end_month IS NULL OR end_month > '201512')
AND ISNULL(disabled,'') != 'Y'
ORDER BY end_month DESC

Related

ORA-01843: not a valid month - Reporting

I have a query that I am using in a PL-SQL view. The view contains a function called Jde_date that takes a date parameter in Julian format and converts it to Gregorian, it works perfectly.
The query is as follows:
select Cedula
, Nombre
, f_nacimiento
, fec_previa
, round(dia) Dia_faltante
, sexo
, Edad
, Fecha_Ingreso
, Nombre_Empresa
, NombreCargo
, Nom_Oficio
, UniddeNegocio
, DesUniNeg
, NombFte
, TipoContrato
, TipoSueldo
, SalHora
, Salario
, cesantias
, prima
, vacaciones
, Total_Prestaciones
, estado
, grupo_cotizante
, tipo_cotizante
, fondo_pensiones
from
(
SELECT distinct total.Cedula
, total.NOMBRE
, total.f_nacimiento
, total.fec_previa
, to_date(total.fec_previa) - sysdate as dia
, total.sexo
, total.Edad
, total.Fecha_Ingreso
, total.Nombre_Empresa
, total.NombreCargo
, total.Nom_Oficio
, total.UniddeNegocio
, Total.DesUniNeg
, total.NombFte
, total.TipoContrato
, total.TipoSueldo
, total.SalHora
, total.Salario
, total.cesantias
, total.prima
, total.vacaciones
, total.Total_Prestaciones
, total.estado
, total.grupo_cotizante
, total.tipo_cotizante
, total.fondo_pensiones
from
(
SELECT * FROM (
select
"F060116"."YAAN8" as AN8,
TRIM("F060116"."YAALPH") as NOMBRE,
TRIM("F060116"."YASSN") as Cedula,
TIPODOC.NNQ70BRTXT as tipo_documento,
"F0010"."CCNAME" as Nombre_Empresa,
"OFI"."DRDL01" as Nom_Oficio,
to_char(integral.JDE_DATE(YADSI), 'dd/mm/yyyy') as Fecha_Ingreso,
"F0005"."DRDL01" as estado,
TRIM(tsal.drdl01) as TipoSueldo,
"Tcon1".drdl01 as TipoContrato
,round(("F060116".yasal/100)/12) as Salario
,round(("F060116".yasal/100)/12/240) as SalHora
,round((("F060116".yasal/100)/12) * 0.0833) as CESANTIAS
,round((("F060116".yasal/100)/12) * 0.0833) as PRIMA
,round((("F060116".yasal/100)/12) * 0.0416) as VACACIONES
,round(((("F060116".yasal/100)/12) * 0.0833) + round((("F060116".yasal/100)/12) * 0.0833) + round((("F060116".yasal/100)/12) * 0.0416)) AS TOTAL_PRESTACIONES
,yasex as sexo
,to_char(integral.JDE_DATE(yadob), 'dd/mm/yyyy') as f_nacimiento
,case
when yasex = 'F' then to_char(add_months(add_months(to_char(integral.JDE_DATE(yadob), 'dd/mm/yyyy'),12*54),-4),'dd/mm/yyyy')
when yasex = 'M' THEN to_char(add_months(add_months(to_char(integral.JDE_DATE(yadob), 'dd/mm/yyyy'),12*59),-4),'dd/mm/yyyy')
END as fec_previa
,TRIM("Fpen"."DRDL01") as fondo_pensiones
,TRIM("gcoti"."DRDL01") as grupo_cotizante
,TRIM("tcoti"."DRDL01") as tipo_cotizante
,to_char(round((sysdate-integral.JDE_DATE(yadob))/365,2)) Edad
,"fte"."DRDL01" as NombFte
,to_char( integral.JDE_DATE(YADT) , 'dd/mm/yyyy') as FechaRetiro
,"F060116"."YAMCU" as UniddeNegocio
,"F0006"."MCDL01" as DesUniNeg
,"F5"."DRDL01" as NombreCargo
from "PRODDTA"."F060116" "F060116"
left join PRODCTL.F0005 TSAL on trim(TSAL.DRKY) = trim(YAP011) --tipo sueldo
and TSAL.DRSY = '06'
and TSAL.DRRT = '11'
left join "PRODCTL"."F0005" "fte" on rtrim(ltrim("fte"."DRKY")) = rtrim("F060116"."YAP005") --Frente trabajo
and "fte"."DRSY" = '06'
AND "fte"."DRRT" = '05'
left join "PRODDTA"."F0006" "F0006" on "F060116"."YAMCU"="F0006"."MCMCU"
left join "PRODCTL"."F0005" "F0005" on rtrim("F060116"."YAPAST")= ltrim("F0005"."DRKY") --Estado Contrato
and "F0005"."DRSY" = '06'
AND "F0005"."DRRT" = 'PS'
left join "PRODDTA"."F0010" "F0010" on "F060116"."YAHMCO" = "F0010"."CCCO"
left join "PRODCTL"."F0005" "F5" on rtrim("F060116"."YAJBCD") = ltrim("F5"."DRKY") --cargo
and "F5"."DRSY" = '06'
AND "F5"."DRRT" = 'G'
left join "PRODCTL"."F0005" "GPO" on rtrim(ltrim("GPO"."DRKY")) = rtrim("F060116"."YAP001") --Grupo de trabajo
and "GPO"."DRSY" = '06'
AND "GPO"."DRRT" = '01'
left join "PRODCTL"."F0005" "OFI" on rtrim(ltrim("OFI"."DRKY")) = rtrim("F060116"."YAP002") --Oficio
and "OFI"."DRSY" = '06'
AND "OFI"."DRRT" = '02'
left join "PRODCTL"."F0005" "fte" on rtrim(ltrim("fte"."DRKY")) = rtrim("F060116"."YAP005") --Ubicacion
and "fte"."DRSY" = '06'
AND "fte"."DRRT" = '05'
left join "PRODCTL"."F0005" "Tcon" on rtrim(ltrim("Tcon"."DRKY")) = rtrim("F060116"."YAP004") --Tipo jornada trabajo
and "Tcon"."DRSY" = '06'
AND "Tcon"."DRRT" = '04'
left join "PRODCTL"."F0005" "Tcon1" on rtrim(ltrim("Tcon1"."DRKY")) = rtrim("F060116"."YAP013") --Tipo de contrato
and "Tcon1"."DRSY" = '06'
AND "Tcon1"."DRRT" = '13'
left join "PRODCTL"."F0005" "Fpen" on rtrim(ltrim("Fpen"."DRKY")) = rtrim("F060116"."YAP017") --Fondo pensiones
and "Fpen"."DRSY" = '06'
AND "Fpen"."DRRT" = '17'
left join "PRODCTL"."F0005" "gcoti" on rtrim(ltrim("gcoti"."DRKY")) = rtrim("F060116"."YAP019") --Grupo cotizante
and "gcoti"."DRSY" = '06'
AND "gcoti"."DRRT" = '19'
left join "PRODCTL"."F0005" "tcoti" on rtrim(ltrim("tcoti"."DRKY")) = rtrim("F060116"."YAP020") --Tipo cotizante
and "tcoti"."DRSY" = '06'
AND "tcoti"."DRRT" = '21'
left join integral.REP_RENOVACION_CONTRATOS rct on trim(rct.CEDULA) = trim("F060116".YASSN)
left join PRODDTA.f01151 correoe on trim(correoe.eaan8) = trim(F060116.yaan8)
and trim(EAIDLN) = '0'
LEFT JOIN proddta.FQ70C014 TIPODOC ON trim(TIPODOC.NNAN8) = trim(F060116.yaan8)
AND NNPN = 0
) me
left join (
select ALADD1 DIRECCION, alan8 from proddta.F0116
where (ALUPMJ,alan8) in
(select max(ALUPMJ),alan8
from proddta.F0116
group by alan8)
group by ALADD1 , alan8 ) direcci
on trim(ME.an8) = trim(direcci.alan8)
left join (
select alan8,drdl01 departamento, ALCTY1 ciudad from proddta.F0116
LEFT JOIN PRODCTL.F0005
ON TRIM(DRKY) = trim(ALADDS)
and DRSY = '00'
AND DRRT = 'S'
where (ALEFTB,alan8) in
(select max(ALEFTB),alan8
from proddta.F0116
group by alan8)
group by alan8 , drdl01,ALCTY1
) ciu
on trim(ciu.alan8) = trim(ME.an8)
left join (
select tel.wpph1 telefono, tel.wpan8
from proddta.F0115 tel
where (tel.WPRCK7,tel.wpan8) in
(select max(tel.WPRCK7),tel.wpan8
from proddta.F0115 tel
where trim(tel.WPPHTP) = 'TEL'
group by tel.wpan8)
group by tel.wpph1 , tel.wpan8
) telt
on trim(ME.an8) = trim(telt.wpan8)
left join (
select celu.wpph1 celular, celu.wpan8
from proddta.F0115 celu
where (celu.WPRCK7,celu.wpan8) in
(select max(celu.WPRCK7),celu.wpan8
from proddta.F0115 celu
where trim(celu.WPPHTP) = 'MOV'
group by celu.wpan8)
group by celu.wpph1 , celu.wpan8
) celut
on trim(ME.an8) = trim(celut.wpan8) ) total
where
((total.estado = 'Active' and total.grupo_cotizante = 'Dependiente' and total.tipo_cotizante ='N/A' and total.sexo ='M'
or (total.estado = 'Active' and total.grupo_cotizante = 'Dependiente' and total.tipo_cotizante ='Depend. pens por vejez activo' and total.sexo ='M')
or (total.estado = 'Active' and total.grupo_cotizante = 'Dependiente' and total.tipo_cotizante ='Cotizante con requisitos cumpl' and total.sexo ='M' )
or (total.estado = 'Active' and total.grupo_cotizante = 'Dependiente' and total.tipo_cotizante ='Cotizante a quién reconoció In' and total.sexo ='M' )
and total.sexo = 'M') AND total.sexo = 'M' and total.edad >=57 and total.edad <=59)
OR
((total.estado = 'Active' and total.grupo_cotizante = 'Dependiente' and total.tipo_cotizante ='N/A' and total.sexo ='F'
or (total.estado = 'Active' and total.grupo_cotizante = 'Dependiente' and total.tipo_cotizante ='Depend. pens por vejez activo' and total.sexo ='F')
or (total.estado = 'Active' and total.grupo_cotizante = 'Dependiente' and total.tipo_cotizante ='Cotizante con requisitos cumpl' and total.sexo ='F' )
or (total.estado = 'Active' and total.grupo_cotizante = 'Dependiente' and total.tipo_cotizante ='Cotizante a quién reconoció In' and total.sexo ='F' )
and total.sexo = 'F') and total.sexo = 'F' and total.edad >=52 and total.edad <=54)
ORDER BY 7 desc)
In the sqldeveolper it works correctly, it returns the information without problems, in the preview of reporting services the same.
But when I publish the report I get the error ORA-01843: not a valid month.
How can I solve that?
to_date(total.fec_previa) - sysdate as dia
You have not specified the format model you are using in the conversion and are relying on the NLS_DATE_FORMAT session parameter to be correct; instead, you should be explicit about the format model you are using:
to_date(total.fec_previa, 'dd/mm/yyyy') - sysdate as dia

SUM 3 different "CASE" columns with three different totals

I'm new to this so I'm sorry if I asked this question wrong. But I'm trying to get 4 different SUM's from my table that uses 4 different cases. But I want the id to be listed only once with the totals. I'll show you what I have, and what I'm trying to get. Please help if possible.
SELECT schools.name, articles.competition_place,
Case when articles.competition = 'yes' and competition_place = '1' then int '100'
when articles.competition = 'yes' and competition_place = '2' then int '60'
when articles.competition = 'yes' and competition_place = '3' then int '20'
ELSE 0 end AS "Competition_Score",
Case when articles.out_reach = 'yes' then int '30'
ELSE 0 end AS "out_reach_Score",
CASE when schools.school_id is not null then int '5'
ELSE 0 end as "article_score",
(Case when articles.competition = 'yes' and competition_place = '1' then int '100'
when articles.competition = 'yes' and competition_place = '2' then int '60'
when articles.competition = 'yes' and competition_place = '3' then int '20'
ELSE 0 end) +
(Case when articles.out_reach = 'yes' then int '30'
ELSE 0 end) +
(CASE when schools.school_id is not null then int '5'
ELSE 0 end) as "total_score"
from articles
join clubs on articles.club_id = clubs.club_id
join schools on clubs.school_id = schools.school_id
My table that I have
And this is what I'm trying to get.
This is the table I'm trying to get
Is this possible?
use aggregation and group by
SELECT schools.name, articles.competition_place,
sum(Case when articles.competition = 'yes' and competition_place = '1' then int '100'
when articles.competition = 'yes' and competition_place = '2' then int '60'
when articles.competition = 'yes' and competition_place = '3' then int '20'
ELSE 0 end) AS "Competition_Score",
sum(Case when articles.out_reach = 'yes' then int '30'
ELSE 0 end) AS "out_reach_Score",
sum(CASE when schools.school_id is not null then int '5'
ELSE 0 end) as "article_score",
sum((Case when articles.competition = 'yes' and competition_place = '1' then int '100'
when articles.competition = 'yes' and competition_place = '2' then int '60'
when articles.competition = 'yes' and competition_place = '3' then int '20'
ELSE 0 end)) +
sum((Case when articles.out_reach = 'yes' then int '30'
ELSE 0 end)) +
sum(CASE when schools.school_id is not null then int '5'
ELSE 0 end)) as "total_score"
from articles
join clubs on articles.club_id = clubs.club_id
join schools on clubs.school_id = schools.school_id
group by schools.name, articles.competition_place

Grouping sets is not aggregating results

I've only recently started using this function, so forgive this question if it is imbecilic.
I have an existing query, which I've realised could be helped with the use of this query to create additional group by groupings, akin to subtotals.
In this example, I am wanting to aggregate in a hierarchy like this:
Year > Month > Profit Centre > Date
An example of the results this query is bringing back
As you can see my grouping sets are returning zero.
My question is, why?
My query is below
SELECT
datepart(yyyy,overview.Date) as 'Year',
datepart(mm,overview.Date) as'Month',
overview.Date as 'Date',
overview.[Profit Centre],
overview.[Current
Year Group Bookings],
overview.[Previous Year Group Bookings],
overview.[Current Year Total Covers],
overview.[Previous Year Total Covers],
overview.[Large Group Count]
FROM
(
SELECT
DISTINCT
CONVERT(date,csd.tendered_date_time) as 'Date',
PCM.profit_center_name as 'Profit Centre',
PCD.profit_center_id,
(
SELECT count(csd2.num_covers)
FROM ig_Business..check_sales_detail csd2
INNER JOIN ig_Dimension..Profit_Center_Dimension PCD2 (NOLOCK) ON
PCD2.profit_center_dim_id = CSD2.profit_center_dim_id and PCD2.ent_id = 1
WHERE PCD2.profit_center_id = PCD.profit_center_id
AND CONVERT(date,CSD2.tendered_date_time) =
CONVERT(date,CSD.tendered_date_time)
AND CSD2.num_covers >=
(CASE
WHEN PCD.profit_center_id = '77' THEN '8'
WHEN PCD.profit_center_id = '13' THEN '10'
WHEN PCD.profit_center_id IN ('60','61','62','63','64','65') THEN '16'
WHEN PCD.profit_center_id = '14' THEN '10'
WHEN PCD.profit_center_id = '90' THEN '10'
WHEN PCD.profit_center_id = '98' THEN '8'
WHEN PCD.profit_center_id IN ('74','101') THEN '10'
WHEN PCD.profit_center_id = '194' THEN '10'
WHEN PCD.profit_center_id = '49' THEN '15'
WHEN PCD.profit_center_id IN ('20','21','22','200') THEN '8'
WHEN PCD.profit_center_id = '74' THEN '15'
WHEN PCD.profit_center_id = '26' THEN '10'
WHEN PCD.profit_center_id IN ('86','68') THEN '8'
WHEN PCD.profit_center_id IN ('40','41','42','43') THEN '8'
WHEN PCD.profit_center_id IN ('96','98','99') THEN '10'
WHEN PCD.profit_center_id = '57' THEN '10'
END)
) as 'Current Year Group Bookings',
(
SELECT count(csd2.num_covers)
FROM ig_Business..check_sales_detail csd2
INNER JOIN ig_Dimension..Profit_Center_Dimension PCD2 (NOLOCK) ON
PCD2.profit_center_dim_id = CSD2.profit_center_dim_id and PCD2.ent_id = 1
WHERE PCD2.profit_center_id = PCD.profit_center_id
AND CONVERT(date,CSD2.tendered_date_time) =
CONVERT(date,DATEADD(month,-12,CSD.tendered_date_time))
AND CSD2.num_covers >=
(CASE
WHEN PCD.profit_center_id = '77' THEN '8'
WHEN PCD.profit_center_id = '13' THEN '10'
WHEN PCD.profit_center_id IN ('60','61','62','63','64','65') THEN '16'
WHEN PCD.profit_center_id = '14' THEN '10'
WHEN PCD.profit_center_id = '90' THEN '10'
WHEN PCD.profit_center_id = '98' THEN '8'
WHEN PCD.profit_center_id IN ('74','101') THEN '10'
WHEN PCD.profit_center_id = '194' THEN '10'
WHEN PCD.profit_center_id = '49' THEN '15'
WHEN PCD.profit_center_id IN ('20','21','22','200') THEN '8'
WHEN PCD.profit_center_id = '74' THEN '15'
WHEN PCD.profit_center_id = '26' THEN '10'
WHEN PCD.profit_center_id IN ('86','68') THEN '8'
WHEN PCD.profit_center_id IN ('40','41','42','43') THEN '8'
WHEN PCD.profit_center_id IN ('96','98','99') THEN '10'
WHEN PCD.profit_center_id = '57' THEN '10'
END)
) as 'Previous Year Group Bookings',
(
SELECT ISNULL(SUM(csd2.num_covers),0)
FROM ig_Business..check_sales_detail csd2
INNER JOIN ig_Dimension..Profit_Center_Dimension PCD2 (NOLOCK) ON
PCD2.profit_center_dim_id = CSD2.profit_center_dim_id and PCD2.ent_id = 1
WHERE PCD2.profit_center_id = PCD.profit_center_id
AND CONVERT(date,CSD2.tendered_date_time) =
CONVERT(date,CSD.tendered_date_time)
AND CSD2.num_covers >=
(CASE
WHEN PCD.profit_center_id = '77' THEN '8'
WHEN PCD.profit_center_id = '13' THEN '10'
WHEN PCD.profit_center_id IN ('60','61','62','63','64','65') THEN '16'
WHEN PCD.profit_center_id = '14' THEN '10'
WHEN PCD.profit_center_id = '90' THEN '10'
WHEN PCD.profit_center_id = '98' THEN '8'
WHEN PCD.profit_center_id IN ('74','101') THEN '10'
WHEN PCD.profit_center_id = '194' THEN '10'
WHEN PCD.profit_center_id = '49' THEN '15'
WHEN PCD.profit_center_id IN ('20','21','22','200') THEN '8'
WHEN PCD.profit_center_id = '74' THEN '15'
WHEN PCD.profit_center_id = '26' THEN '10'
WHEN PCD.profit_center_id IN ('86','68') THEN '8'
WHEN PCD.profit_center_id IN ('40','41','42','43') THEN '8'
WHEN PCD.profit_center_id IN ('96','98','99') THEN '10'
WHEN PCD.profit_center_id = '57' THEN '10'
END)
) as 'Current Year Total Covers',
(
SELECT ISNULL(SUM(csd2.num_covers),0)
FROM ig_Business..check_sales_detail csd2
INNER JOIN ig_Dimension..Profit_Center_Dimension PCD2 (NOLOCK) ON
PCD2.profit_center_dim_id = CSD2.profit_center_dim_id and PCD2.ent_id = 1
WHERE PCD2.profit_center_id = PCD.profit_center_id
AND CONVERT(date,CSD2.tendered_date_time) =
CONVERT(date,DATEADD(month,-12,CSD.tendered_date_time))
AND CSD2.num_covers >=
(CASE
WHEN PCD.profit_center_id = '77' THEN '8'
WHEN PCD.profit_center_id = '13' THEN '10'
WHEN PCD.profit_center_id IN ('60','61','62','63','64','65') THEN '16'
WHEN PCD.profit_center_id = '14' THEN '10'
WHEN PCD.profit_center_id = '90' THEN '10'
WHEN PCD.profit_center_id = '98' THEN '8'
WHEN PCD.profit_center_id IN ('74','101') THEN '10'
WHEN PCD.profit_center_id = '194' THEN '10'
WHEN PCD.profit_center_id = '49' THEN '15'
WHEN PCD.profit_center_id IN ('20','21','22','200') THEN '8'
WHEN PCD.profit_center_id = '74' THEN '15'
WHEN PCD.profit_center_id = '26' THEN '10'
WHEN PCD.profit_center_id IN ('86','68') THEN '8'
WHEN PCD.profit_center_id IN ('40','41','42','43') THEN '8'
WHEN PCD.profit_center_id IN ('96','98','99') THEN '10'
WHEN PCD.profit_center_id = '57' THEN '10'
END)
) as 'Previous Year Total Covers',
(CASE
WHEN PCD.profit_center_id = '77' THEN '8'
WHEN PCD.profit_center_id = '13' THEN '10'
WHEN PCD.profit_center_id IN ('60','61','62','63','64','65') THEN '16'
WHEN PCD.profit_center_id = '14' THEN '10'
WHEN PCD.profit_center_id = '90' THEN '10'
WHEN PCD.profit_center_id = '98' THEN '8'
WHEN PCD.profit_center_id IN ('74','101') THEN '10'
WHEN PCD.profit_center_id = '194' THEN '10'
WHEN PCD.profit_center_id = '49' THEN '15'
WHEN PCD.profit_center_id IN ('20','21','22','200') THEN '8'
WHEN PCD.profit_center_id = '74' THEN '15'
WHEN PCD.profit_center_id = '26' THEN '10'
WHEN PCD.profit_center_id IN ('86','68') THEN '8'
WHEN PCD.profit_center_id IN ('40','41','42','43') THEN '8'
WHEN PCD.profit_center_id IN ('96','98','99') THEN '10'
WHEN PCD.profit_center_id = '57' THEN '10'
END) AS 'Large Group Count'
FROM ig_business..Check_Sales_Detail CSD (NOLOCK)
INNER JOIN ig_Dimension..Profit_Center_Dimension PCD (NOLOCK) ON
PCD.profit_center_dim_id = CSD.profit_center_dim_id and PCD.ent_id = 1
INNER JOIN it_cfg..Profit_Center_Master PCM (NOLOCK) ON PCM.profit_center_id
= PCD.profit_center_id and PCm.ent_id = 1
WHERE
(
(pcd.profit_center_id = '77' AND csd.num_covers > 8)
OR
(pcd.profit_center_id = '13' AND csd.num_covers >= 10)
OR
(pcd.profit_center_id IN ('60','61','62','63','64','65') AND
csd.num_covers > 16)
OR
(pcd.profit_center_id = 14 AND csd.num_covers >= 10)
OR
(pcd.profit_center_id = 90 AND csd.num_covers >= 10)
OR
(pcd.profit_center_id = 98 AND csd.num_covers >= 8)
OR
(pcd.profit_center_id IN ('74','101') AND csd.num_covers >= 10)
OR
(pcd.profit_center_id = '194' AND csd.num_covers >= 10)
OR
(pcd.profit_center_id = '49' AND csd.num_covers >= 15)
OR
(pcd.profit_center_id IN ('20','21','22','200') AND csd.num_covers >= 8)
OR
(pcd.profit_center_id = '74' AND csd.num_covers >= 15)
OR
(pcd.profit_center_id = '26' AND csd.num_covers >= 10)
OR
(pcd.profit_center_id IN ('86','68') AND csd.num_covers >= 8)
OR
(pcd.profit_center_id IN ('40','41','42','43') AND csd.num_covers >= 8)
OR
(pcd.profit_center_id IN ('96','98','99') AND csd.num_covers >= 10)
OR
(pcd.profit_center_id = '57' AND csd.num_covers >= 10)
)
AND
CSD.tendered_date_time > CONVERT(date,'2017-01-01') -- We only want
comparisons from today going forward, i.e. not historical
GROUP BY
GROUPING SETS
(
(csd.tendered_date_time, PCM.profit_center_name,PCD.profit_center_id),
(datepart(yyyy,csd.tendered_date_time),datepart(mm,csd.tendered_date_time),
pcm.profit_center_name),
()
)
) overview
ORDER BY overview.[Profit Centre] asc, CONVERT(date,overview.Date) asc
My question is, why (are the grouping sets zero)?
Because you are not using aggregate functions such as SUM() or COUNT() in a manner than can be summarised into sub-totals. You are using a set of "correlated subqueries" which do use COUNT() but by the time these are evaluated the outer query just sees those columns as data (not as aggregates).
example (untested of course):
WITH pcd AS (
SELECT *
FROM ig_Dimension..Profit_Center_Dimension pcd
WHERE (
OR (pcd.profit_center_id = '13' AND csd.num_covers >= 10)
OR (pcd.profit_center_id = 14 AND csd.num_covers >= 10) -- is it an integer? or not?
OR (pcd.profit_center_id = '26' AND csd.num_covers >= 10)
OR (pcd.profit_center_id = '49' AND csd.num_covers >= 15)
OR (pcd.profit_center_id = '57' AND csd.num_covers >= 10)
OR (pcd.profit_center_id = '74' AND csd.num_covers >= 15)
OR (pcd.profit_center_id = '77' AND csd.num_covers > 8)
OR (pcd.profit_center_id = 90 AND csd.num_covers >= 10) -- is it an integer? or not?
OR (pcd.profit_center_id = 98 AND csd.num_covers >= 8) -- is it an integer? or not?
OR (pcd.profit_center_id = '194' AND csd.num_covers >= 10)
OR (pcd.profit_center_id IN ('20', '21', '22', '200') AND csd.num_covers >= 8)
OR (pcd.profit_center_id IN ('40', '41', '42', '43') AND csd.num_covers >= 8)
OR (pcd.profit_center_id IN ('60', '61', '62', '63', '64', '65') AND csd.num_covers > 16)
OR (pcd.profit_center_id IN ('74', '101') AND csd.num_covers >= 10)
OR (pcd.profit_center_id IN ('86', '68') AND csd.num_covers >= 8)
OR (pcd.profit_center_id IN ('96', '98', '99') AND csd.num_covers >= 10)
)
AND pcd.ent_id = 1
)
SELECT
DATEPART(yyyy, csd.tendered_date_time) AS 'Year'
, DATEPART(mm, csd.tendered_date_time) AS 'Month'
, pcd.[Profit Centre]
, pcm.profit_center_name AS 'Profit Centre'
, pcd.profit_center_id
, COUNT(csd.num_covers)
FROM ig_business..Check_Sales_Detail csd
INNER JOIN pcd ON pcd.profit_center_dim_id = csd.profit_center_dim_id
INNER JOIN it_cfg..Profit_Center_Master pcm ON pcm.profit_center_id = pcd.profit_center_id
AND pcm.ent_id = 1
GROUP BY GROUPING SETS
( DATEPART(yyyy, csd.tendered_date_time) AS 'Year'
, DATEPART(mm, csd.tendered_date_time) AS 'Month'
, pcd.[Profit Centre]
, pcm.profit_center_name AS 'Profit Centre'
, pcd.profit_center_id
)
NOTE: you need to be careful about "implicit conversions", if pcd.profit_center_id is an integer then do NOT use '194', but if it is a varchar or similar then do not use integers. I also suggest you try to keep that where clause in some "order" so it is easier to read.

TSQL convert list of IP addresses to CIDR notation

Given a table with the following IP Addresses
IPAddress
-----------
192.168.1.1
192.168.1.2
192.168.1.3
192.168.1.4
192.168.1.5
192.168.1.6
192.168.1.7
192.168.1.8
I'm looking for the following output
Output
---------------
192.168.1.0/29
192.168.1.8/32
The closest I've come was with this:
SELECT SUBSTRING(IPAddress, 1, LEN(IPAddress) - CHARINDEX('.',REVERSE(IPAddress))), COUNT(*)
FROM IP
GROUP BY SUBSTRING(IPAddress, 1, LEN(IPAddress) - CHARINDEX('.',REVERSE(IPAddress)))
But that only gets me the subnet and # of address. Not sure how to take the next step.
You will need the subnet-mask in order to know the correct amount of host bits for your notation.
This will give you CIDR:
DECLARE #IPADDRESS VARCHAR(15) = '192.168.1.1'
,#NETMASK VARCHAR(15) = '255.255.255.0'
,#NETWORKBITS VARCHAR(3)
SET #NETWORKBITS =
CASE
WHEN #NETMASK = '255.0.0.0' THEN '8'
WHEN #NETMASK = '255.128.0.0' THEN '9'
WHEN #NETMASK = '255.192.0.0' THEN '10'
WHEN #NETMASK = '255.224.0.0' THEN '11'
WHEN #NETMASK = '255.240.0.0' THEN '12'
WHEN #NETMASK = '255.248.0.0' THEN '13'
WHEN #NETMASK = '255.252.0.0' THEN '14'
WHEN #NETMASK = '255.254.0.0' THEN '15'
WHEN #NETMASK = '255.255.0.0' THEN '16'
WHEN #NETMASK = '255.255.128.0' THEN '17'
WHEN #NETMASK = '255.255.192.0' THEN '18'
WHEN #NETMASK = '255.255.224.0' THEN '19'
WHEN #NETMASK = '255.255.240.0' THEN '20'
WHEN #NETMASK = '255.255.248.0' THEN '21'
WHEN #NETMASK = '255.255.252.0' THEN '22'
WHEN #NETMASK = '255.255.254.0' THEN '23'
WHEN #NETMASK = '255.255.255.0' THEN '24'
WHEN #NETMASK = '255.255.255.128' THEN '25'
WHEN #NETMASK = '255.255.255.192' THEN '26'
WHEN #NETMASK = '255.255.255.224' THEN '27'
WHEN #NETMASK = '255.255.255.240' THEN '28'
WHEN #NETMASK = '255.255.255.248' THEN '29'
WHEN #NETMASK = '255.255.255.252' THEN '30'
WHEN #NETMASK = '255.255.255.254' THEN '31'
WHEN #NETMASK = '255.255.255.255' THEN '32'
END
PRINT #IPADDRESS + '/' #NETWORKBITS

Can someone show me how to add these fields to this Stored Procedure

I have a SP that was built for us that does a summary statement of tables in our DB. What I am trying to do is make it so the SP also pulls that last year/month of data as well based on the date entered. Below is the SQL code I am working with. What I am trying to get is a total and Volume field that is the sum based on the date parameter entered minus 1 month.
For example:
If I put in 2013 10 01 start and 2013 10 31 end I would get the total and volume for 2013-10-01 to 2013-10-31 and in 2 separate columns the total and volume for 2013-09-01 to 1013-09-30
Code
(
#Start DATETIME,
#End DATETIME
)
AS
DECLARE
#reference int,
#sSQL VARCHAR(2000)
BEGIN
select Convert(datetime,Cast(edi.Creation_dt as varchar(8)),103) as Date, ia.xref_no_tx, la.ldc_acct_no, la.serv_loc_nm
, a.acct_nm, c.company_last_nm
, Case RG.Rate_cd
When 'DLS' then 'HEDGE'
When 'STL' then 'STL'
WHen 'SPOT BILLING' then 'SPOT'
WHen 'SL SPOT' then 'STL SPOT'
Else null
End as Acct_type
, Convert(datetime,Cast(ia.start_dt as varchar(8)),103)as Start_dt
, Convert(datetime,Cast(ia.end_dt as varchar(8)),103) as End_dt
, edi.trans_sub_ty as Inv_type
, max( case when la.class_ty_cd = 'COMM' and th.ppa_in = 'N' and th.trans_sub_ty_cd = 'FEES' then th.trans_qty
when la.class_ty_cd = 'MUNI' and th.ppa_in = 'N' and th.trans_sub_ty_cd = 'EXCS' then th.trans_qty
when la.class_ty_cd <> 'COMM' and th.ppa_in = 'N' and th.trans_sub_ty_cd = 'BASE' then th.trans_qty
else 0 end) as Volume
, sum(th.trans_am) as Total
from invoice_advise_relate iar, transaction_history th
,invoice_advise ia, ldc_account la, account a, customer c, edi_transaction edi
, (select max(edi_trans_id) as m_edi_trans, relate_id from edi_transaction where class_nm = 'cInvoiceAdvise' group by relate_id) as edic
, (Select max(rating_group_id) as m_rate, ldc_acct_id from rating_group group by ldc_acct_Id) as C_Rate
, rating_group rg
where iar.trans_id = th.trans_id
and th.cancel_in = 'N'
and th.trans_ty_cd not in ('PAY', 'ANC')
and iar.inv_adv_id = ia.inv_adv_id
and ia.ldc_acct_id = la.ldc_acct_id
and la.acct_id = a.acct_id
and a.cust_id = c.cust_id
and la.ldc_acct_no not like 'E%'
and edi.Creation_dt >= convert(varchar,#Start,112)
and edi.Creation_dt <= convert(varchar,#End,112)
and edi.relate_id = ia.inv_adv_id
and edic.m_edi_trans = edi.edi_trans_id
and edi.response_cd = ''
and rg.rating_group_id = C_Rate.M_Rate
and C_Rate.LDC_Acct_Id = la.ldc_Acct_Id
and edi.trans_sub_ty <> '00'
group by edi.Creation_dt, ia.xref_no_tx, la.ldc_acct_no,la.serv_loc_nm, a.acct_nm, c.company_last_nm, ia.start_dt, ia.end_dt,edi.trans_sub_ty, rg.rate_cd
Start off by declaring and initializing a start date for the previous month.
DECLARE #PrevStart datetime
SELECT #PrevStart = dateadd(month, -1, #Start)
In your WHERE clause substitute the previous start date for start date so that you include last month's data as well as this month's.
and edi.Creation_dt >= convert(varchar,#PrevStart,112)
and edi.Creation_dt <= convert(varchar,#End,112)
Then you filter last month's data from this month's using CASE statement logic.
, max( case when la.class_ty_cd = 'COMM' and th.ppa_in = 'N' and th.trans_sub_ty_cd = 'FEES'
AND edi.Creation_dt >= convert(varchar,#Start,112) then th.trans_qty
when la.class_ty_cd = 'MUNI' and th.ppa_in = 'N' and th.trans_sub_ty_cd = 'EXCS'
AND edi.Creation_dt >= convert(varchar,#Start,112) then th.trans_qty
when la.class_ty_cd <> 'COMM' and th.ppa_in = 'N' and th.trans_sub_ty_cd = 'BASE'
AND edi.Creation_dt >= convert(varchar,#Start,112) then th.trans_qty
else 0 end) as Volume
, sum(CASE WHEN edi.Creation_dt >= convert(varchar,#Start,112) THEN th.trans_am ELSE 0 END) as Total
, max( case when la.class_ty_cd = 'COMM' and th.ppa_in = 'N' and th.trans_sub_ty_cd = 'FEES'
AND edi.Creation_dt < convert(varchar,#Start,112) then th.trans_qty
when la.class_ty_cd = 'MUNI' and th.ppa_in = 'N' and th.trans_sub_ty_cd = 'EXCS'
AND edi.Creation_dt < convert(varchar,#Start,112) then th.trans_qty
when la.class_ty_cd <> 'COMM' and th.ppa_in = 'N' and th.trans_sub_ty_cd = 'BASE'
AND edi.Creation_dt < convert(varchar,#Start,112) then th.trans_qty
else 0 end) as PrevVolume
, sum(CASE WHEN edi.Creation_dt < convert(varchar,#Start,112) THEN th.trans_am ELSE 0 END) as PrevTotal