how to Replace null with zero in pivot SQL query - sql-server

I am trying to fetch Year wise and month wise sales like
select * from
(
select year(InvDt) as [Year], left(datename(Month,InvDt), 3) as [Month],
InvAmnt as Amount
from tblInvoice where TenantId =-xxxxxxxx
) as Inv
pivot
(sum(Amount) for [Month] in(Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep,
Oct, Nov, [Dec])) as pvt
But here so many null is coming so I want to replace these null with zero.
please help me.

create table tblInvoice (InvDt date, TenantId int, InvAmnt numeric)
insert into tblInvoice values ('20180601',1,1),('20180601',1,1),('20180601',1,1),('20180501',1,1), ('20180401',1,1)
SELECT Year
, COALESCE(Jan ,0) Jan
, COALESCE(Feb ,0) Feb
, COALESCE(Mar ,0) Mar
, COALESCE(Apr ,0) Apr
, COALESCE(May ,0) May
, COALESCE(Jun ,0) Jun
, COALESCE(Jul ,0) Jul
, COALESCE(Aug ,0) Aug
, COALESCE(Sep ,0) Sep
, COALESCE(Oct ,0) Oct
, COALESCE(Nov ,0) Nov
, COALESCE(Dec ,0) Dec
FROM ( SELECT YEAR(InvDt) AS Year
, LEFT(DATENAME(MONTH, InvDt), 3) AS Month
, InvAmnt AS Amount
FROM tblInvoice
WHERE TenantId = 1) AS Inv
PIVOT ( SUM(Amount)
FOR Month IN (Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec)) AS pvt;

So Answer is this but it's too long, something we must have another solution but I am not getting right now
select [Year], isnull(Jan, 0) as Jan,isnull(Feb,0) as Feb, isnull(Mar, 0) as
Mar, isnull(Apr, 0) as Apr, isnull(May,0) as May,
isnull(Jun,0) as Jun, isnull(Jul,0) as Jul, isnull(Aug,0) as Aug,
isnull(Sep,0) as Sep,isnull(Oct,0) as Oct, isnull(Nov,0) as Nov,
isnull([Dec],0) as Dec
from
(
select year(InvDt) as [Year], left(datename(Month,InvDt), 3) as [Month],
InvAmnt as Amount
from tblInvoice where TenantId =-xxxxxxx
) as Inv
pivot
(sum(Amount) for [Month] in(Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep,
Oct, Nov, [Dec])) as pvt
Thanks Mazhar by your solution my mind was opened and works this.

Just add a coalesce statement in a subquery to replace nulls on zero:
select * from
(
select year(InvDt) as [Year], left(datename(Month,InvDt), 3) as [Month],
coalesce(InvAmnt, 0) as Amount
from tblInvoice where TenantId =-xxxxxxxx
) as Inv
pivot
(sum(Amount) for [Month] in(Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep,
Oct, Nov, [Dec])) as pvt)

Related

How to GROUP BY Month() but shifted?

I'm wondering how could I use the GROUP BY on month, but from the n-th of a month to the (n-1)-th of the next month. For exemple, I want to GROUP by from the 20 of january to the 19 of february, from the 20 of february to the 19 of march...
Currently I can GROUP BY Months and dates <20 with a condition. There is the demo :
https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=8b55b7df44350c4ad3c595d03e421b6e
But now I don't know how can I group the 'false' of a month (ie that the value is the sum for days > 20) with the 'true' of the next month.
Does anyone as a idea how to do that ?(maybe what i'm trying os not the good way how to do that)
For each date before the 20th you can subtract 1 month and group it with the previous month:
WITH cte AS (
SELECT CASE
WHEN DAY(Date) >= 20 THEN Date
ELSE DATEADD(mm, -1, Date)
END Date,
Value
FROM tablename
)
SELECT YEAR(Date) year, MONTH(Date) month, SUM(Value) val
FROM cte
GROUP BY YEAR(Date), MONTH(Date)
ORDER BY YEAR(Date), MONTH(Date)
Or you can change the CASE expression to:
CASE
WHEN DAY(Date) < 20 THEN Date
ELSE DATEADD(mm, 1, Date)
END
so that all dates after the 19th are grouped with the next month.
Or:
SELECT FORMAT(DATEADD(dd, -20, Date), 'yyyy-MM') year_month,
SUM(Value) val
FROM tablename
GROUP BY FORMAT(DATEADD(dd, -20, Date), 'yyyy-MM')
See the demo.

COALESCE working in only one case

I am trying to update an ERP software and I block on a syntax in a table made with PIVOTS
Let me explain, I would like in my table (which is functional) that all NULL values ​​be replaced by a 0.
In another table almost identical with the same syntax I succeeded but in the other, the COALESCEs do not work .. I'm stuck on it for quite some time. If someone can enlighten me ..
Here is the beginning of the code for the table where the COALESCE functions (I put only the beginning because the code makes 500 lines and the remainder remains the same)
DECLARE #VALEUR VARCHAR(10)
SET #VALEUR = RTRIM(CAST(:A_USER AS VARCHAR(10)))
--Cette valeur va correspondre à l'id de la personne connectée
SET language us_english
DECLARE #P_A_USER VARCHAR(10)
SELECT #P_A_USER = VALEUR FROM T_PARAMETRE
WHERE PARAGRAPHE = 'COD_PRTDIRCOMM'
DECLARE #COD_GRP VARCHAR(10)
SELECT #COD_GRP = COD_GRP FROM USERS WHERE COD_USER = #VALEUR
IF #P_A_USER = 'GBL'
BEGIN
SET #P_A_USER = NULL
END
SELECT *
FROM (SELECT 'CA Total facturé' AS DONNEE
UNION
SELECT 'Marge total (en €)' AS DONNEE
UNION
SELECT 'Marge total (en %)' AS DONNEE
UNION
SELECT 'CA Exploitation facturé' AS DONNEE
UNION
SELECT 'Marge Exploitation (en €)' AS DONNEE
UNION
SELECT 'Marge Exploitation (en %)' AS DONNEE
UNION
SELECT 'CA Service facturé' AS DONNEE
UNION
SELECT 'Marge Service (en €)' AS DONNEE
UNION
SELECT 'Marge Service (en %)' AS DONNEE
UNION
SELECT 'CA Solution facturé' AS DONNEE
UNION
SELECT 'Marge Solution facturé (en €)' AS DONNEE
UNION
SELECT 'Marge Solution facturé (en %)' AS DONNEE) Q
LEFT OUTER JOIN (
-----------------------------------DEBUT TOTAL----------------------------
SELECT donnee,
NUMLIGNE,
COALESCE(january, 0) AS JANUARY,
COALESCE(february, 0) AS FEBRUARY,
COALESCE(march, 0) AS MARCH,
COALESCE(april, 0) AS APRIL,
COALESCE(may, 0) AS MAY,
COALESCE(june, 0) AS JUNE,
COALESCE(july, 0) AS JULY,
COALESCE(august, 0) AS AUGUST,
COALESCE(september, 0) AS SEPTEMBER,
COALESCE(october, 0) AS OCTOBER,
COALESCE(november, 0) AS NOVEMBER,
COALESCE(december, 0) AS DECEMBER
FROM (SELECT Datename(month, date_facture) AS 'MOIS'
,
Cast(Sum(n1)AS DECIMAL (18, 2)) AS
'CA_Total_mois',
'CA total facturé' AS 'DONNEE',
'A' AS 'NUMLIGNE'
FROM v_facture
WHERE cod_com = ISNULL(#P_A_USER, cod_com)
AND Year(date_facture) = '2016'
GROUP BY Datename(month, date_facture)) AS ca_total_mois
PIVOT(Sum(ca_total_mois)
FOR mois IN (january,
february,
march,
april,
may,
june,
july,
august,
september,
october,
november,
december)) AS pvt1
-------------------------------------------------------------------------
UNION ALL
SELECT donnee,
NUMLIGNE,
COALESCE(january, 0) AS JANUARY,
COALESCE(february, 0) AS FEBRUARY,
COALESCE(march, 0) AS MARCH,
COALESCE(april, 0) AS APRIL,
COALESCE(may, 0) AS MAY,
COALESCE(june, 0) AS JUNE,
COALESCE(july, 0) AS JULY,
COALESCE(august, 0) AS AUGUST,
COALESCE(september, 0) AS SEPTEMBER,
COALESCE(october, 0) AS OCTOBER,
COALESCE(november, 0) AS NOVEMBER,
COALESCE(december, 0) AS DECEMBER
FROM (SELECT Datename(month, date_facture) AS 'MOIS',
Cast(Sum(n2)AS DECIMAL (18, 2)) AS
'Marge_Total_mois',
'Marge total (en €)' AS 'DONNEE',
'B' AS 'NUMLIGNE'
FROM v_facture
WHERE cod_com = ISNULL(#P_A_USER, cod_com)
AND Year(date_facture) = '2016'
GROUP BY Datename(month, date_facture)) AS
Marge_Total_Mois
PIVOT(Sum(marge_total_mois)
FOR mois IN (january,
february,
march,
april,
may,
june,
july,
august,
september,
october,
november,
december)) AS pvt2
------------------------------------------------------------------------
UNION ALL
-- Etc ...
-- The end :
) Q2
ON Q2.donnee = Q.donnee
ORDER BY NUMLIGNE ASC
Here is the table he refers to:
1st TABLE
And here is the code where the COALESCEs do not work:
DECLARE #VALEUR VARCHAR(10)
SET #VALEUR = RTRIM(CAST(:A_USER AS VARCHAR(10)))
-- This value will match the id of the connected person
SET language us_english
DECLARE #P_A_USER VARCHAR(10)
SELECT #P_A_USER = VALEUR FROM T_PARAMETRE
WHERE PARAGRAPHE = 'COD_PRTDIRCOMM'
DECLARE #COD_GRP VARCHAR(10)
SELECT #COD_GRP = COD_GRP FROM USERS WHERE COD_USER = #VALEUR
IF #P_A_USER = 'GBL'
BEGIN
SET #P_A_USER = NULL
END
SELECT *
FROM (SELECT 'Nouveaux contrats' AS DONNEE
UNION
SELECT 'Contrats Renouvelés' AS DONNEE
UNION
SELECT 'RDV Réalisés' AS DONNEE
UNION
SELECT 'RDV Planifiés' AS DONNEE
UNION
SELECT 'Nouveaux comptes ouverts' AS DONNEE
UNION
SELECT 'Nouvelles affaires' AS DONNEE
UNION
SELECT 'Nvl affaires avec exploitations' AS DONNEE
UNION
SELECT 'CA Nouvelles affaires (€)' AS DONNEE
UNION
SELECT 'Affaires gagnées' AS DONNEE
UNION
SELECT 'Affaires perdues' AS DONNEE
UNION
SELECT 'Taux affaires gagnées' AS DONNEE) Q
LEFT OUTER JOIN (
-----------------------------------DEBUT TOTAL----------------------------
SELECT donnee,
NUMLIGNE,
COALESCE(january, 0) AS JANUARY,
COALESCE(february, 0) AS FEBRUARY,
COALESCE(march, 0) AS MARCH,
COALESCE(april, 0) AS APRIL,
COALESCE(may, 0) AS MAY,
COALESCE(june, 0) AS JUNE,
COALESCE(july, 0) AS JULY,
COALESCE(august, 0) AS AUGUST,
COALESCE(september, 0) AS SEPTEMBER,
COALESCE(october, 0) AS OCTOBER,
COALESCE(november, 0) AS NOVEMBER,
COALESCE(december, 0) AS DECEMBER
FROM (SELECT Datename(month, d1) AS 'MOIS'
,
Cast(Count(*)AS DECIMAL (18, 2)) AS
'Total_Nouveaux_Contrats',
'Nouveaux contrats' AS 'DONNEE',
'A' AS 'NUMLIGNE'
FROM contrat
WHERE c22 = ISNULL(#P_A_USER, c22)
AND Month(D1)= MONTH(getdate())
AND C27 = 'Nouveau contrat'
GROUP BY Datename(month, d1)) AS Total_Nouveaux_Contrats
PIVOT(Sum(Total_Nouveaux_Contrats)
FOR mois IN (january,
february,
march,
april,
may,
june,
july,
august,
september,
october,
november,
december)) AS pvt1
-------------------------------------------------------------------------
UNION ALL
SELECT donnee,
NUMLIGNE,
COALESCE(january, 0) AS JANUARY,
COALESCE(february, 0) AS FEBRUARY,
COALESCE(march, 0) AS MARCH,
COALESCE(april, 0) AS APRIL,
COALESCE(may, 0) AS MAY,
COALESCE(june, 0) AS JUNE,
COALESCE(july, 0) AS JULY,
COALESCE(august, 0) AS AUGUST,
COALESCE(september, 0) AS SEPTEMBER,
COALESCE(october, 0) AS OCTOBER,
COALESCE(november, 0) AS NOVEMBER,
COALESCE(december, 0) AS DECEMBER
FROM (SELECT Datename(month, d1) AS 'MOIS',
Cast(Count(*)AS DECIMAL (18, 2)) AS
'Total_Contrats_Renouveles',
'Contrats Renouvelés' AS 'DONNEE',
'B' AS 'NUMLIGNE'
FROM contrat
WHERE c22 = ISNULL(#P_A_USER, c22)
AND Month(D1)= MONTH(getdate())
AND ( c27 = NULL
OR c27 = 'nouveau contrat' )
GROUP BY Datename(month, d1)) AS
Total_Contrats_Renouveles
PIVOT(Sum(Total_Contrats_Renouveles)
FOR mois IN (january,
february,
march,
april,
may,
june,
july,
august,
september,
october,
november,
december)) AS pvt2
------------------------------------------------------------------------
UNION ALL
-- ETC ...
-- La fin :
) Q2
ON Q2.donnee = Q.donnee
ORDER BY NUMLIGNE ASC
And here is the table it returns such a user for both for which there is not much value
2nd TABLE
I noticed that as long as there is a value in a row that is different from 0, then it will display all the other values ​​of that row that are null at 0 (the coalesces would work in this case there o_O)
So, sorry for the novel and thank you for your attention!
I am using SSMS for test my request but I use the code in the ERP software
I haven't much to go on here but it looks like a missing 's'. I think the COALESCE is working but the LEFT OUTER JOIN is not.
SELECT *
FROM (SELECT 'Nouveaux contrats' AS DONNEE
UNION
and later
WHERE c22 = ISNULL(#P_A_USER, c22)
AND Month(D1)= MONTH(getdate())
AND ( c27 = NULL
OR c27 = 'nouveau contrat' )
GROUP BY Datename(month, d1)) AS
Try including the name from both sides of the join to ensure the row is coming back at all.

PIVOT with Grand Total

I'm working with PIVOT in SQL, something I've only started learning about this week. I'm trying to get a grand total for each Director as an added column at the side. I've looked online and seen its a popular query, but the ways of doing it seem really confusing and a little over-kill for what I need. Can someone show me how I'd add a grand total column at the end of each row that just adds up the monthly numbers for each Director?
SELECT *
FROM (
SELECT
DimDirectoR.Full_Name, YEAR(dim_Date.Date) as [year],left(datename(month,dim_Date.Date),3)as [month],
Fact_Stream.Device_Type_ID as Amount
FROM Fact_Stream INNER JOIN DimDirector ON Fact_Stream.Director_ID=DimDirector.Director_ID
INNER JOIN dim_Date
on Fact_Stream.Request_View_Date = dim_Date.ID
) as Directors
PIVOT
(
COUNT(Amount)
FOR [month] IN (jan, feb, mar, apr,
may, jun, jul, aug, sep, oct, nov, dec)
)AS DirectorsMonthlyStreams
ORDER BY [year], Full_Name
Current output:
I simply want to have a column which says 'Total' at the end of each row displaying the total amount for that directors year...
SQL Server 2012
You can just do a sum in the top level select statement:
SELECT *, jan+feb+mar+apr+may+jun+jul+aug+sep+oct+nov+dec Total
FROM (
SELECT
DimDirectoR.Full_Name, YEAR(dim_Date.Date) as [year],left(datename(month,dim_Date.Date),3)as [month],
Fact_Stream.Device_Type_ID as Amount
FROM Fact_Stream INNER JOIN DimDirector ON Fact_Stream.Director_ID=DimDirector.Director_ID
INNER JOIN dim_Date
on Fact_Stream.Request_View_Date = dim_Date.ID
) as Directors
PIVOT
(
COUNT(Amount)
FOR [month] IN (jan, feb, mar, apr,
may, jun, jul, aug, sep, oct, nov, dec)
)AS DirectorsMonthlyStreams
ORDER BY [year], Full_Name
You could do something like this as well:
SQL - Pivot with Grand Total Column and Row

Trying To Join Two Pivot SQL Query Queries

I've created two sql queries, the first sums Qty of 12 months and the second sums value over 12 months. Im trying to merge these into one query, but no matter what I try it errors.
The expect output would be 24 columns on one row e.g. Jan, JanQty, Feb, FebQty, Mar, MarQty etc.
Any help would be great!
First Query (Qty):
SELECT
SUM(JanQty) as 'JanQty',
SUM(FebQty) as 'FebQty',
SUM(MarQty) as 'MarQty',
SUM(AprQty) as 'AprQty',
SUM(MayQty) as 'MayQty',
SUM(JuneQty) as 'JuneQty',
SUM(JulyQty) as 'JulyQty',
SUM(AugQty) as 'AugQty',
SUM(SeptQty) as 'SeptQty',
SUM(OctQty) as 'OctQty',
SUM(NovQty) as 'NovQty',
SUM(DecQty) as 'DecQty'
from (
SELECT
ISNULL([1],0) as JanQty,
ISNULL([2],0) as FebQty,
ISNULL([3],0) as MarQty,
ISNULL([4],0) as AprQty,
ISNULL([5],0) as MayQty,
ISNULL([6],0) as JuneQty,
ISNULL([7],0) as JulyQty,
ISNULL([8],0) as AugQty,
ISNULL([9],0) as SeptQty,
ISNULL([10],0) as OctQty,
ISNULL([11],0) as NovQty,
ISNULL([12],0) as DecQty
from
(select SUM(T0.Quantity) as QtyBal,
MONTH(T1.DocDate) as Month
from INV1 T0
inner join OINV T1 on t0.DocEntry = t1.DocEntry
where t1.DocDate BETWEEN '20140101' AND '20141231' and
year(T1.DocDate) = 2014
group by t0.Quantity, t1.DocDate) s
Pivot
(SUM(QtyBal) FOR Month IN ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12])) p
Union ALL
SELECT
ISNULL([1],0) as JanQty,
ISNULL([2],0) as FebQty,
ISNULL([3],0) as MarQty,
ISNULL([4],0) as AprQty,
ISNULL([5],0) as MayQty,
ISNULL([6],0) as JuneQty,
ISNULL([7],0) as JulyQty,
ISNULL([8],0) as AugQty,
ISNULL([9],0) as SeptQty,
ISNULL([10],0) as OctQty,
ISNULL([11],0) as NovQty,
ISNULL([12],0) as DecQty
from
(select SUM(-T0.Quantity) as QtyBal,
MONTH(T1.DocDate) as Month
from RIN1 T0
inner join ORIN T1 on t0.DocEntry = t1.DocEntry
where t1.DocDate BETWEEN '20140101' AND '20141231' and
year(T1.DocDate) = 2014
group by -t0.Quantity, t1.DocDate) s
Pivot
(SUM(QtyBal) FOR Month IN ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12])) p
) sq
Second Query (Value):
SELECT
SUM(Jan) as 'Jan',
SUM(Feb) as 'Feb',
SUM(Mar) as 'Mar',
SUM(Apr) as 'Apr',
SUM(May) as 'May',
SUM(June) as 'June',
SUM(July) as 'July',
SUM(Aug) as 'Aug',
SUM(Sept) as 'Sept',
SUM(oct) as 'Oct',
SUM(nov) as 'Nov',
SUM(Dec) as 'Dec'
from (
SELECT
ISNULL([1],0) as Jan,
ISNULL([2],0) as Feb,
ISNULL([3],0) as Mar,
ISNULL([4],0) as Apr,
ISNULL([5],0) as May,
ISNULL([6],0) as June,
ISNULL([7],0) as July,
ISNULL([8],0) as Aug,
ISNULL([9],0) as Sept,
ISNULL([10],0) as Oct,
ISNULL([11],0) as Nov,
ISNULL([12],0) as Dec
from
(select SUM(T0.LineTotal) as Bal,
MONTH(T1.DocDate) as Month
from INV1 T0
inner join OINV T1 on t0.DocEntry = t1.DocEntry
where t1.DocDate BETWEEN '20140101' AND '20141231' and
year(T1.DocDate) = 2014
group by t0.LineTotal, t1.DocDate) s
Pivot
(SUM(Bal) FOR Month IN ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12])) p
Union ALL
SELECT
ISNULL([1],0) as Jan,
ISNULL([2],0) as Feb,
ISNULL([3],0) as Mar,
ISNULL([4],0) as Apr,
ISNULL([5],0) as May,
ISNULL([6],0) as June,
ISNULL([7],0) as July,
ISNULL([8],0) as Aug,
ISNULL([9],0) as Sept,
ISNULL([10],0) as Oct,
ISNULL([11],0) as Nov,
ISNULL([12],0) as Dec
from
(select SUM(-T0.LineTotal) as Bal,
MONTH(T1.DocDate) as Month
from RIN1 T0
inner join ORIN T1 on t0.DocEntry = t1.DocEntry
where t1.DocDate BETWEEN '20140101' AND '20141231' and
year(T1.DocDate) = 2014
group by -t0.LineTotal, t1.DocDate) s
Pivot
(SUM(Bal) FOR Month IN ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12])) p
) sq
Try using a CROSS JOIN:
SELECT
Jan,
JanQty
FROM
(
SELECT
SUM(JanQty) as 'JanQty',
SUM(FebQty) as 'FebQty',
SUM(MarQty) as 'MarQty',
SUM(AprQty) as 'AprQty',
SUM(MayQty) as 'MayQty',
SUM(JuneQty) as 'JuneQty',
SUM(JulyQty) as 'JulyQty',
SUM(AugQty) as 'AugQty',
SUM(SeptQty) as 'SeptQty',
SUM(OctQty) as 'OctQty',
SUM(NovQty) as 'NovQty',
SUM(DecQty) as 'DecQty'
FROM
(
SELECT
ISNULL([1],0) as JanQty,
ISNULL([2],0) as FebQty,
ISNULL([3],0) as MarQty,
ISNULL([4],0) as AprQty,
ISNULL([5],0) as MayQty,
ISNULL([6],0) as JuneQty,
ISNULL([7],0) as JulyQty,
ISNULL([8],0) as AugQty,
ISNULL([9],0) as SeptQty,
ISNULL([10],0) as OctQty,
ISNULL([11],0) as NovQty,
ISNULL([12],0) as DecQty
FROM
(
SELECT
SUM(T0.Quantity) as QtyBal,
MONTH(T1.DocDate) as Month
FROM
INV1 T0
inner join
OINV T1 on t0.DocEntry = t1.DocEntry
WHERE
t1.DocDate BETWEEN '20140101' AND '20141231' and
year(T1.DocDate) = 2014
GROUP BY t0.Quantity, t1.DocDate
) s
PIVOT
(
SUM(QtyBal) FOR
Month IN ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12])
) p
UNION ALL
SELECT
ISNULL([1],0) as JanQty,
ISNULL([2],0) as FebQty,
ISNULL([3],0) as MarQty,
ISNULL([4],0) as AprQty,
ISNULL([5],0) as MayQty,
ISNULL([6],0) as JuneQty,
ISNULL([7],0) as JulyQty,
ISNULL([8],0) as AugQty,
ISNULL([9],0) as SeptQty,
ISNULL([10],0) as OctQty,
ISNULL([11],0) as NovQty,
ISNULL([12],0) as DecQty
from
(
select
SUM(-T0.Quantity) as QtyBal,
MONTH(T1.DocDate) as Month
from
RIN1 T0
inner join
ORIN T1 on t0.DocEntry = t1.DocEntry
where
t1.DocDate BETWEEN '20140101' AND '20141231' and
year(T1.DocDate) = 2014
group by -t0.Quantity, t1.DocDate) s
Pivot
(
SUM(QtyBal) FOR
Month IN ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12])
) p
) sqa
) qty
CROSS JOIN
(
SELECT
SUM(Jan) as 'Jan',
SUM(Feb) as 'Feb',
SUM(Mar) as 'Mar',
SUM(Apr) as 'Apr',
SUM(May) as 'May',
SUM(June) as 'June',
SUM(July) as 'July',
SUM(Aug) as 'Aug',
SUM(Sept) as 'Sept',
SUM(oct) as 'Oct',
SUM(nov) as 'Nov',
SUM(Dec) as 'Dec'
FROM
(
SELECT
ISNULL([1],0) as Jan,
ISNULL([2],0) as Feb,
ISNULL([3],0) as Mar,
ISNULL([4],0) as Apr,
ISNULL([5],0) as May,
ISNULL([6],0) as June,
ISNULL([7],0) as July,
ISNULL([8],0) as Aug,
ISNULL([9],0) as Sept,
ISNULL([10],0) as Oct,
ISNULL([11],0) as Nov,
ISNULL([12],0) as Dec
FROM
(
SELECT
SUM(T0.LineTotal) as Bal,
MONTH(T1.DocDate) as Month
FROM
INV1 T0
inner join
OINV T1 on t0.DocEntry = t1.DocEntry
WHERE
t1.DocDate BETWEEN '20140101' AND '20141231' and
year(T1.DocDate) = 2014
GROUP BY t0.LineTotal, t1.DocDate
) s
PIVOT
(
SUM(Bal) FOR
Month IN ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12])
) p
UNION ALL
SELECT
ISNULL([1],0) as Jan,
ISNULL([2],0) as Feb,
ISNULL([3],0) as Mar,
ISNULL([4],0) as Apr,
ISNULL([5],0) as May,
ISNULL([6],0) as June,
ISNULL([7],0) as July,
ISNULL([8],0) as Aug,
ISNULL([9],0) as Sept,
ISNULL([10],0) as Oct,
ISNULL([11],0) as Nov,
ISNULL([12],0) as Dec
from
(
select
SUM(-T0.LineTotal) as Bal,
MONTH(T1.DocDate) as Month
from
RIN1 T0
inner join
ORIN T1 on t0.DocEntry = t1.DocEntry
where
t1.DocDate BETWEEN '20140101' AND '20141231' and
year(T1.DocDate) = 2014
group by -t0.LineTotal, t1.DocDate
) s
Pivot
(
SUM(Bal) FOR
Month IN ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12])
) p
) sqb
) Bal

Cumulative sum based on months in a year with NULL Months

I am trying to return a summary of all prospects entered in the system for a chosen sales person and a chosen year. The date entered is a datetime and I am pivoting the data to show it broken by month to month.
The first query returns the number of referrals each month, where the second query shows how many referrals entered cumulatively. I have gotten them properly showing with the exception of months containing null values. Months with null values I want to show the value of the previous month in that case.
I am currently using T-SQL 2012.
SELECT 'Number of Referrals' AS Measure,[1] AS Jan, [2] AS Feb, [3] AS Mar, [4] AS Apr,
[5] AS May, [6] AS Jun, [7] AS Jul, [8] AS Aug, [9] AS Sep, [10] AS Oct, [11] AS Nov, [12] AS Dec
FROM
(
SELECT ISNULL(COUNT(DISTINCT CSCU.ClientID), 0) AS Referrals, DATEPART(M, CS.DateAdded) AS Months
FROM ClientTracker.dbo.ClientService CS
INNER JOIN ClientTracker.dbo.ClientServiceContactUser CSCU
ON CS.ClientID = CSCU.ClientID
AND CS.ServiceID = CSCU.ServiceID
WHERE UserId = #UserID
AND DATEPART(YEAR, CS.DateAdded) = #Year
AND CSCU.ServiceID = 30
GROUP BY DATEPART(M, CS.DateAdded)
) AS S
PIVOT
(
SUM(Referrals)
FOR [Months] IN ([1], [2], [3], [4],
[5], [6], [7], [8], [9], [10], [11], [12])
)AS PV
UNION
SELECT 'Number of Referrals Cumulative' AS Measure,[1] AS Jan, [2] AS Feb, [3] AS Mar, [4] AS Apr, [5] AS May, [6] AS Jun, [7] AS Jul, [8] AS Aug, [9] AS Sep, [10] AS Oct, [11] AS Nov, [12] AS Dec
FROM
(
SELECT DATEPART(M, CS.DateAdded) AS Months,
SUM(COUNT(CSCU.ClientID)) OVER (ORDER BY DATEPART(M, CS.DateAdded)) AS Cumulative
FROM ClientTracker.dbo.ClientService CS
INNER JOIN ClientTracker.dbo.ClientServiceContactUser CSCU
ON CS.ClientID = CSCU.ClientID
AND CS.ServiceID = CSCU.ServiceID
WHERE UserId = #UserID
AND DATEPART(YEAR, CS.DateAdded) = #Year
AND CSCU.ServiceID = 30
GROUP BY DATEPART(M, CS.DateAdded)
) AS S
PIVOT
(
SUM(Cumulative)
FOR [Months] IN ([1], [2], [3], [4],
[5], [6], [7], [8], [9], [10], [11], [12])
)AS PV
You could use coalesce() function. It takes in as many parameters and returns the first non null values.
So for in your example rewrite the query to
SELECT 'Number of Referrals' AS Measure,[1] AS Jan, coalesce([2],[1]) AS Feb, .....
COALESCE() on MSDN

Resources