How do I case sum a column based on a value - 1? - sql

So I have the following 2 columns
,sum(case when Owner_Faculty_Full_Desc = 'Business and Law Faculty' then 1 else 0 end) [Business Current Year]
,sum(case when Owner_Faculty_Full_Desc = 'Business and Law Faculty' AND Apps.Reporting_Year = (Apps.Reporting_Year - 1) then 1 else 0 end) [Business Previous Year]
Lets say that Apps.ReportingYear is 2011, how to I get the second column to sum all values in 2010? I thought my statement would work but it doesn't seem to be.
Here is the entire query
WITH Equiv_day AS (
SELECT Date_Key, Sem1_Equivalent_Day
FROM [AUTDataWarehouse].[dbo].[Dim_Date]
WHERE Full_Date = CONVERT(DATE, GETDATE())
),
Date_list AS (
SELECT dt.Date_Key, dt.Calendar_Year
FROM [AUTDataWarehouse].[dbo].[Dim_Date] AS dt
INNER JOIN Equiv_day AS ed
ON (ed.Sem1_Equivalent_Day - 1) = dt.Sem1_Equivalent_Day
AND dt.Calendar_Year IN (YEAR(GETDATE()), YEAR(GETDATE())-1, YEAR(GETDATE()) - 2, YEAR(GETDATE()) - 3, YEAR(GETDATE()) - 4, YEAR(GETDATE()) - 5)
),
PYTD_Outcome_by_Application AS (
SELECT
se.Reporting_Year,
f.Student_Demographics_Key,
f.Application_Code,
Outcome_Row = Max(f.Application_Row_Num)
FROM AUTDataWarehouse.dbo.Fact_Admission as f
INNER JOIN AUTDataWarehouse.dbo.Dim_Intake as it
ON it.Intake_Key = f.Intake_Key
AND it.Prog_Intake_Type_Desc = 'Intake'
INNER JOIN AUTDataWarehouse.dbo.Dim_Semester as se
ON se.Semester_Key = f.Semester_Key
INNER JOIN AUTDataWarehouse.dbo.Dim_Campus as cp
ON cp.Campus_Key = f.Campus_Key
INNER JOIN Date_list as dates
ON dates.Calendar_Year = se.Reporting_Year
WHERE f.Last_Change_Date_Key < dates.Date_Key
GROUP BY
se.Reporting_Year,
f.Student_Demographics_Key,
f.Application_Code
),
Applications_Count AS (
SELECT
p.Owner_Faculty_Full_Desc,
p.Programme_Full_Desc,
et.Enrolment_Type_Key,
se.Reporting_Year,
sd.Last_Secondary_School_Name [LastSchoolName],
pr.Programme_Key,
Campus = CASE WHEN cp.Campus_Name IN ('South','South Dist') THEN 'South' ELSE 'City / North Shore' END,
se.Semester_Desc,
f.Student_Demographics_Key,
Applicants = COUNT(DISTINCT f.Student_Demographics_Key)
FROM AUTDataWarehouse.dbo.Fact_Admission as f
INNER JOIN AUTDataWarehouse.dbo.Dim_Student_Demographics as sd ON sd.Student_Demographics_Key = f.Student_Demographics_Key
INNER JOIN AUTDataWarehouse.dbo.Dim_Programme as P on P.Programme_Key = f.Programme_Key
INNER JOIN AUTDataWarehouse.dbo.Dim_Intake as it
ON it.Intake_Key = f.Intake_Key
AND it.Prog_Intake_Type_Desc = 'Intake'
INNER JOIN AUTDataWarehouse.dbo.Dim_Enrolment_Type as et
ON et.Enrolment_Type_Key = f.Enrolment_Type_Key
INNER JOIN AUTDataWarehouse.dbo.Dim_Programme as pr
ON pr.Programme_Key = f.Programme_Key
INNER JOIN AUTDataWarehouse.dbo.Dim_Campus as cp
ON cp.Campus_Key = f.Campus_Key
INNER JOIN AUTDataWarehouse.dbo.Dim_Semester as se
ON se.Semester_Key = f.Semester_Key
INNER JOIN Date_list as dates
ON dates.Calendar_Year = se.Reporting_Year
INNER JOIN PYTD_Outcome_by_Application AS pytd
ON pytd.Application_Code = f.Application_Code
AND pytd.Student_Demographics_Key = f.Student_Demographics_Key
AND pytd.Outcome_Row = f.Application_Row_Num
and pytd.Reporting_Year = se.Reporting_Year
AND pytd.Application_Code IS NOT NULL
GROUP BY
sd.Last_Secondary_School_Name,
p.Owner_Faculty_Full_Desc,
p.Programme_Full_Desc,
et.Enrolment_Type_Key,
se.Reporting_Year,
pr.Programme_Key,
CASE WHEN cp.Campus_Name IN ('South','South Dist') THEN 'South' ELSE 'City / North Shore' END,
se.Semester_Desc,
f.Student_Demographics_Key
)
SELECT
CAST(EP.Educational_Provider_Key as varchar(10)) as 'Education Key'
,[LastSchoolName]
,Owner_Faculty_Full_Desc
,Programme_Full_Desc
,Apps.Reporting_Year
,cast(cast(Apps.Reporting_Year as varchar(255)) + '0101' as datetime) as [YearTime]
,sum(case when Owner_Faculty_Full_Desc = 'Business and Law Faculty' then 1 else 0 end) [Business and Law Current Year]
,sum(case when Owner_Faculty_Full_Desc = 'Business and Law Faculty' AND (Apps.Reporting_Year = Apps.Reporting_Year - 1) then 1 else 0 end) [Business and Law Previous Year]
,sum(case when Owner_Faculty_Full_Desc = 'Culture and Society Faculty' then 1 else 0 end) [Culture and Society Current Year]
,sum(case when Owner_Faculty_Full_Desc = 'Culture and Society Faculty' AND Apps.Reporting_Year = 2014 then 1 else 0 end) [Culture and Society Previous Year]
,sum(case when Owner_Faculty_Full_Desc = 'Design & Creative Technologies Faculty'then 1 else 0 end) [Design & Creative TechnologiesCurrent Year]
,sum(case when Owner_Faculty_Full_Desc = 'Design & Creative Technologies Faculty' AND Apps.Reporting_Year = (Apps.Reporting_Year - 1) then 1 else 0 end) [Design & Creative Technologies Previous Year]
,sum(case when Owner_Faculty_Full_Desc = 'Health & Environmental Sciences Faculty'then 1 else 0 end) [Health & Environmental Sciences Current Year]
,sum(case when Owner_Faculty_Full_Desc = 'Health & Environmental Sciences Faculty' AND Apps.Reporting_Year = (Apps.Reporting_Year - 1) then 1 else 0 end) [Health & Environmental Sciences Previous Year]
,sum(case when Owner_Faculty_Full_Desc = 'Te Ara Poutama' then 1 else 0 end) [Te Ara Poutama Current Year]
,sum(case when Owner_Faculty_Full_Desc = 'Te Ara Poutama' AND Apps.Reporting_Year = (Apps.Reporting_Year - 1) then 1 else 0 end) [Te Ara Poutama Previous Year]
,sum(apps.Applicants) [Total Applicants]
FROM Applications_Count as Apps
inner join AUTDataWarehouse.dbo.Dim_Educational_Provider as EP on EP.Provider_Name = [LastSchoolName]
GROUP BY Apps.Reporting_Year, [LastSchoolName], EP.Educational_Provider_Key,Owner_Faculty_Full_Desc
, Programme_Full_Desc
ORDER BY Apps.Reporting_Year, [Total Applicants] DESC
So basically for each programme I want a column for total applicants for the ReportingYear then total applicants for the Reporting Year - 1
Thanks!

Probably easiest to calculate the years separately, then self-join to get the value for the previous year. This is the basic logic you would use, although obviously you will need to make it more complex when you adapt it to the long query above:
;with CTE as (select ReportingYear
, sum(case when [condition] then 1 else 0 end) as ValueCurrYear
from MyTables
group by ReportingYear)
Select a.*, b.ValueCurrYear as ValuePreviousYear
from CTE a
left join CTE b
on a.ReportingYear = b.ReportingYear + 1

Related

Messy SQL Query Needs to be more Efficient

THIS Data pull needs help. The efficiency/performance sucks and I don't know enough about SQL to make it better. I'm in the middle of a project that required me to learn SQL pretty fast, but considering the time frame I'm looking at, I've come to YOU, the PROS.... Any ideas from the pros to make this for efficient?
SELECT
d.[Date] AS [Date],
LEFT(CONVERT(VARCHAR,d.[Date],112),6) AS [YearMo],
FORMAT(d.[Date],'MMMM') AS [Month],
YEAR(d.[Date]) AS [Year],
e.[MbrNo] AS [Member ID],
e.[Mkt_State] AS [Mkt State],
e.[Mkt] AS [Mkt Segment],
COALESCE(e.[Individual_Premium_Amt],0) AS [Individual Premium],
COALESCE(e.[Total_Premium_Amt],0) AS [Total Premium],
COALESCE(v.[Inpatient_Pd],0) AS [Inpatient Pd],
COALESCE(v.[Outpatient_Pd],0) AS [Outpatient Pd],
COALESCE(v.[Professional_Pd],0) AS [Professional Pd],
COALESCE(v.[Other_Pd],0) AS [Other Pd],
COALESCE(v.[Med_Pd],0) AS [Med Pd],
COALESCE(SUM(v.[Med_Pd]) OVER (PARTITION BY e.[MbrNo],YEAR(d.[Date])),0) AS [Total Med Pd YTD],
COALESCE(v.[Med_Allowed],0) AS [Med Allowed],
COALESCE(v.[Rx_Pd],0) AS [Rx Pd],
COALESCE(SUM(v.[Rx_Pd]) OVER (PARTITION BY e.[MbrNo],YEAR(d.[Date])),0) AS [Total RX Pd YTD],
COALESCE(v.[Rx_Allowed],0) AS [Rx Allowed],
COALESCE(v.[Med_RX_Pd],0) AS [Med Rx Pd],
COALESCE(SUM(v.[Med_Pd] + v.[Rx_Pd]) OVER (PARTITION BY e.[MbrNo],YEAR(d.[Date])
ORDER BY e.[MbrNo],LEFT(CONVERT(VARCHAR,d.[Date],112),6) ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW),0) AS [RS Med Rx Pd],
COALESCE(SUM(v.[Med_Pd]) OVER (PARTITION BY e.[MbrNo],YEAR(d.[Date]))
+ SUM(v.[Rx_Pd]) OVER (PARTITION BY e.[MbrNo],YEAR(d.[Date])),0) AS [Total Pd YTD],
COALESCE(v.[Med_RX_Allowed],0) AS [Med Rx Allowed],
CASE
WHEN ((SUM(v.[Med_Pd] + v.[Rx_Pd]) OVER (PARTITION BY e.[MbrNo],YEAR(d.[Date]))) > rr.[Recover_Threshold])
THEN ((SUM(v.[Med_Pd] + v.[Rx_Pd]) OVER (PARTITION BY e.[MbrNo],YEAR(d.[Date])) - rr.[Recover_Threshold]))
ELSE 0
END AS [Recoverable Amt],
SUM(1.0) OVER (PARTITION BY e.[MbrNo],YEAR(d.[Date])) AS [MM (Yearly)],
CASE
WHEN ((SUM(v.[Med_Pd] + v.[Rx_Pd]) OVER (PARTITION BY e.[MbrNo],YEAR(d.[Date]))) > rr.[Recover_Threshold])
THEN ((SUM(v.[Med_Pd] + v.[Rx_Pd]) OVER (PARTITION BY e.[MbrNo],YEAR(d.[Date])) - rr.[Recover_Threshold]))
/ SUM(1.0) OVER (PARTITION BY e.[MbrNo],YEAR(d.[Date]))
ELSE 0
END AS [Recoverable Amtv2],
COALESCE(rr.[Members],0) AS [Members],
COALESCE(rr.[MM],0) AS [MM],
COALESCE(rr.[Rx_Rebates],0) AS [Rx Rebates],
COALESCE(rr.[RA_PMPM],0) AS [RA PMPM],
COALESCE(rr.[RA_Payable],0) AS [RA Payable],
COALESCE(rr.[Pd_Threshold],0) AS [SR Pd Threshold],
COALESCE(rr.[Recover_Threshold],0) AS [SR Recover Threshold],
COALESCE(rr.[CF_Inpatient_PMPM],0) AS [CF IP PMPM],
COALESCE(rr.[CF_Outpatient_PMPM],0) AS [CF OP PMPM],
COALESCE(rr.[CF_Professional_PMPM],0) AS [CF PROF PMPM],
COALESCE(rr.[CF_RX_PMPM],0) AS [CF RX PMPM],
COALESCE(rr.[CF_Med_PMPM],0) AS [CF Med PMPM],
COALESCE(SUM(rr.[CF_RX_PMPM])+(rr.[CF_Med_PMPM]),0) AS [CF Med_Rx PMPM]
FROM -- Date Scaffold - Each month starting 20170101 to the current GETDATE() month
(SELECT
DATEADD(MONTH,number,'20190101') AS [Date],
EOMONTH(DATEADD(MONTH,number,'20190101')) AS [EOM Date]
FROM MASTER..[spt_values]
WHERE TYPE='P'
AND DATEADD(MONTH,number,'20190101') <= GETDATE()
) AS d
INNER JOIN -- Join Med enrollment for each month to the date scaffold, creating the membermonths format
(SELECT
e.*
FROM [SomeDB].[dbo].[sometable] AS e
WHERE [benefitType]=930700000
AND e.[LOB]='Commercial'
AND e.[Segment_Cancelled]<>'Yes'
AND e.[Mbr_Status]<>'Pending Binder Payment'
AND e.[MbrNo]<>0
) AS e
ON e.[Start_Date]<=d.[Date] AND e.[End_Date]>=d.[EOM Date]
LEFT JOIN
(SELECT
c.[YEARMO],
c.[MEMBERID],
SUM(CASE WHEN c.[UTILGRP]='INPATIENT' THEN c.[Pd] ELSE 0 END) AS [Inpatient_Pd],
SUM(CASE WHEN c.[UTILGRP]='OUTPATIENT' THEN c.[Pd] ELSE 0 END) AS [Outpatient_Pd],
SUM(CASE WHEN c.[UTILGRP]='PROFESSIONAL' THEN c.[Pd] ELSE 0 END) AS [Professional_Pd],
SUM(CASE WHEN [UTILGRP]='OTHER' THEN c.[Pd] ELSE 0 END) AS [Other_Pd],
SUM(CASE WHEN c.[CLAIMTYPE]='Med' THEN c.[Pd] ELSE 0 END) AS [Med_Pd],
SUM(CASE WHEN c.[CLAIMTYPE]='Med' THEN c.[ALLOWED] ELSE 0 END) AS [Med_Allowed],
SUM(CASE WHEN c.[CLAIMTYPE]='Pharmacy' THEN c.[Pd] ELSE 0 END) AS [Rx_Pd],
SUM(CASE WHEN c.[CLAIMTYPE]='Pharmacy' THEN c.[ALLOWED] ELSE 0 END) AS [Rx_ALlowed],
SUM(CASE WHEN c.[CLAIMTYPE]='Med' OR c.[CLAIMTYPE]='Pharmacy' THEN c.[Pd] ELSE 0 END) AS [Med_RX_Pd],
SUM(CASE WHEN c.[CLAIMTYPE]='Med' OR c.[CLAIMTYPE]='Pharmacy' THEN c.[ALLOWED] ELSE 0 END) AS [Med_RX_Allowed]
FROM [SomeDB].[dbo].[SomeTable] AS c
WHERE c.[MbrNo] <> 0
AND c.[CLAIMLINESTATUS] NOT IN ('D','V')
AND c.[LOB]='IND'
GROUP BY c.[YearMo],c.[MbrNo]
) AS v
ON e.[MbrNo]=v.[MbrNo] AND LEFT(CONVERT(VARCHAR,d.[Date],112),6)=v.[YearMo]
LEFT JOIN [SomeDB].[dbo].[SomeTable] AS rr
ON e.[Mkt_Segment]=rr.[Mkt_Segment] AND LEFT(CONVERT(VARCHAR,d.[Date],112),6)=rr.[YearMo]
GROUP BY d.[Date],e.[MbrNo],e.[Mkt_State],e.[Mkt_Segment],e.[Individual_Premium_Amt],e.[Total_Premium_Amt],
v.[Inpatient_Pd],v.[Outpatient_Pd],v.[Professional_Pd],v.[Other_Pd],v.[Med_Pd],v.[Med_Allowed],v.[Rx_Pd],v.[Rx_Allowed],v.[Med_RX_Pd],v.[Med_RX_Allowed],
rr.[Members],rr.[MM],rr.[Rx_Rebates],rr.[RA_PMPM],rr.[RA_Payable],rr.[Pd_Threshold],rr.[Recover_Threshold],rr.[CF_Inpatient_PMPM],rr.[CF_Outpatient_PMPM],rr.[CF_Professional_PMPM],rr.[CF_RX_PMPM],rr.[CF_Med_PMPM]
I would replace all the <> 0 statements (Which is typically not SARGable) with >0 statements which is Sargable.

Convert column to row and sum query in different table

i trying to figure to convert sumtchtraffic and totalpayloadGb column in sitetable and sum data totalpayloadGb & sumtchtraffic where BTS_TYPE 2g, 3g and 4g in techtable
i tried like this, but i cant show totalpayloadgb & sumtchtraffic in column [SUM OF] ([sum of] is not in any table in my database)
select * from (select
sum(case when techtable.BTS_TYPE='2G' then sitetable.TotalPayloadGb else 0 end) as [Total 2G],
sum(case when techtable.BTS_TYPE='3G' then sitetable.TotalPayloadGb else 0 end) as [Total 3G],
sum (case when techtable.BTS_TYPE='4G'then sitetable.TotalPayloadGb else 0 end) as [Total 4G]
from sitetable
inner join techtable on sitetable.sitename = techtable.sitename) as t
I want show my data like this:
One way would be to total your results separately, using the same conditional aggregation you have started, and then UNION the results together. Since your first column doesn't exist anywhere else, you'll have to hard-code it into the queries.
SELECT
'TotalPayloadGb' AS SumOf,
sum(CASE WHEN t.BTS_TYPE = '2G' THEN s.TotalPayloadGb ELSE 0 END) AS [Total 2G],
sum(CASE WHEN t.BTS_TYPE = '3G' THEN s.TotalPayloadGb ELSE 0 END) AS [Total 3G],
sum(CASE WHEN t.BTS_TYPE = '4G' THEN s.TotalPayloadGb ELSE 0 END) AS [Total 4G]
FROM sitetable AS s
INNER JOIN techtable AS t
ON s.sitename = t.sitename
UNION
SELECT
'SumTCHTraffic' AS SumOf,
sum(CASE WHEN t.BTS_TYPE = '2G' THEN s.SumTCHTraffic ELSE 0 END) AS [Total 2G],
sum(CASE WHEN t.BTS_TYPE = '3G' THEN s.SumTCHTraffic ELSE 0 END) AS [Total 3G],
sum(CASE WHEN t.BTS_TYPE = '4G' THEN s.SumTCHTraffic ELSE 0 END) AS [Total 4G]
FROM sitetable AS s
INNER JOIN techtable AS t
ON s.sitename = t.sitename;
Depending on what you are trying to do, you could do like this:
SELECT tt.BTS_Type, sum(st.TotalPayloadDb)
FROM SiteTable st
INNER JOIN TechTable as tt on st.sitename = tt.sitename
This will give one row per BTS_Type value.

sum case issue , no column for groupby clause

I have the query:
SELECT leads,
touched,
invalid,
TQL,
SQOs,
Wins,
(touched / (CONVERT(decimal(7, 2), leads)) * 100) AS [touch%],
(t.invalid / touched) AS [Invalid Leads%],
(TQL / (CONVERT(decimal(7, 2), touched)) * 100) AS [TQL %],
(SQOs / (CONVERT(decimal(7, 2), TQL)) * 100) AS [SQO%],
(Wins / (CONVERT(decimal(7, 2), TQL)) * 100) AS [Wins%]
FROM (SELECT COUNT([lead id]) AS leads,
SUM(CASE
WHEN a.status = 'Disqualified'
OR a.status = 'Qualified'
AND a.[Status Reason] <> 'Expired' THEN 1
ELSE 0
END) AS touched,
SUM(CASE
WHEN a.status = 'Disqualififed'
AND a.[Status Reason] IN ('Already Engaged', 'Already purchased', 'Invalid Contact Info', 'Misrouted Lead', 'Non-Supported Market', 'Partner') THEN 1
ELSE 0
END) AS invalid,
SUM(CASE WHEN a.status = 'Qualified' THEN 1 ELSE 0 END) AS TQL,
SUM(CASE WHEN b.status = 'Open' THEN 1 ELSE 0 END) AS SQOs,
SUM(CASE WHEN b.status = 'Won' THEN 1 ELSE 0 END) AS Wins,
CASE WHEN b.status = 'Won' THEN SUM([End Cust Purchase Amount Const $])END AS tqlrevenue
FROM lead a
LEFT JOIN opportunity b ON a.[Opportunity Id (Qualifying Opportunity) (Opportunity)] = b.[Opportunity Id]
LEFT JOIN MSSalesMalaysia_Updated c ON b.[Opportunity Id] = c.[opp id]
WHERE a.[Lead Source] = 'Marketing') t;
When I add the expression case when B.status ='Won' then sum([End Cust Purchase Amount Const $]) end as tqlrevenue I get the following error:
Column 'opportunity.Status' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
Now all columns in subquery are case conditions, which column to include?
You probably want conditional aggregation:
sum(case when B.status ='Won' then [End Cust Purchase Amount Const $]) end) as tqlrevenue
That is, the case expression is the argument to sum().

Subquery to pull sum amount from different table and group by salesperson

--I am trying to simply add one subquery to take the total sales of each salesperson in relation to their quotes. I am at a loss and hopefully someone can help.
select sp.FIRST_NAME + ' ' + sp.LAST_NAME,
sum(case when sq.SAL_QUOTE_STATUS_ID = '1' then 1 else 0 end) as [Created],
sum(case when sq.SAL_QUOTE_STATUS_ID = '4' then 1 else 0 end) as [Ordered],
sum(case when sq.SAL_QUOTE_STATUS_ID = '3' then 1 else 0 end) as [Rejected],
sum(sq.AMOUNT_INCLUDING_TAX) as [Amount],
sum(sq.COST) as [Cost],
sum(sq.AMOUNT_INCLUDING_TAX - sq.COST) as [Profit],
round(100 * (case when sum(sq.AMOUNT_INCLUDING_TAX) > 0 then
(sum(sq.AMOUNT_INCLUDING_TAX) -
sum(sq.COST)) / sum(sq.AMOUNT_INCLUDING_TAX) else 0 end), 3) as [GP%],
(Select sum(so.amount_including_tax)
from SAL_SALES_ORDER so
where so.SALESPERSON_ID = sp.SALESPERSON_ID) as [YTD Sales]
from SAL_SALES_QUOTE sq
inner join CRM_SALESPERSON sp on sp.SALESPERSON_ID = sq.SALESPERSON_ID
where sq.CREATED_DATE > '01-01-2018'
group by sp.FIRST_NAME + ' ' + sp.LAST_NAME
I took your subquery out of the select, made it into a result set to join on , and then pulled the sum from there.
select sp.FIRST_NAME + ' ' + sp.LAST_NAME,
sum(case when sq.SAL_QUOTE_STATUS_ID = '1' then 1 else 0 end) as [Created],
sum(case when sq.SAL_QUOTE_STATUS_ID = '4' then 1 else 0 end) as [Ordered],
sum(case when sq.SAL_QUOTE_STATUS_ID = '3' then 1 else 0 end) as [Rejected],
sum(sq.AMOUNT_INCLUDING_TAX) as [Amount],
sum(sq.COST) as [Cost],
sum(sq.AMOUNT_INCLUDING_TAX - sq.COST) as [Profit],
round(100 * (case when sum(sq.AMOUNT_INCLUDING_TAX) > 0 then
(sum(sq.AMOUNT_INCLUDING_TAX) -
sum(sq.COST)) / sum(sq.AMOUNT_INCLUDING_TAX) else 0 end), 3) as [GP%],
sum([x.ytd_sales]) AS YTD_Sales
from SAL_SALES_QUOTE sq
inner join CRM_SALESPERSON sp on sp.SALESPERSON_ID = sq.SALESPERSON_ID
inner join (Select so.salesperson_id, sum(so.amount_including_tax) AS [YTD Sales]
from SAL_SALES_ORDER so
group by so.salesperson_id) x
ON x.salesperson_id = sp.salesperson_id
where sq.CREATED_DATE > '01-01-2018'
group by sp.FIRST_NAME + ' ' + sp.LAST_NAME

Rows to columns in SQL Server

I'm developping a tool which generates an excel table with SQL results.
I have several days, several payment methods (fe: credit card, check, species) and several sums.
I am doing this request :
SELECT TE.DATE AS 'JOUR', SUM(TE.TOTAL_TTC) AS 'CA TTC', ME.LIBELLE AS 'LIBELLE'
FROM TICKET TE
INNER JOIN MODE_REGLEMENT ME ON ME.CODE = TE.MODE_REGLEMENT
GROUP BY TE.DATE, ME.LIBELLE
(MODE_REGLEMENT means payment method)
And i have this result :
**JOUR** **CA TTC** **LIBELLE**
07/03/2014 1409.66 CREDIT CARD
07/03/2014 70 CHECK
07/03/2014 1393.31 SPECIES
08/03/2014 3368.07 CREDIT CARD
08/03/2014 599.44 SPECIES
09/03/2014 268.7 CREDIT CARD
09/03/2014 174.62 CHECK
But i'm searching to generate something like that :
**JOUR** **CA TTC** **CREDIT CARD** **CHECK** **SPECIES**
07/03/2014 2872.97 1409.66 70 1393.31
08/03/2014 3967.51 3368.07 0 599.44
09/03/2014 443.32 268.7 174.62 0
The column 'CA TTC' will be the sum of each payment methods.
Can you please help me to do a request (for SQL Server) to have the result i want.
Thank you a lot !
(sorry for the bad english i'm french)
You need to use PIVOT
Find the total per JOUR using SUM over() in pivot source query.
SELECT jour,
CA_TTC=total,
[CREDIT CARD]=Isnull([CREDIT CARD], 0),
[CHECK]=Isnull([CHECK], 0),
[SPECIES]=Isnull([SPECIES], 0)
FROM (SELECT *,
Sum(CA_TTC)OVER(partition BY JOUR) total
FROM Your_result) a
PIVOT (Max(CA_TTC)
FOR LIBELLE IN([CREDIT CARD],
[CHECK],
[SPECIES])) pv
SQLFIDDLE DEMO
Another method is to use conditional aggregation or SUM(CASE WHEN ... END):
;WITH CTE([JOUR], [CA TTC], [LIBELLE]) AS(
SELECT
TE.DATE AS 'JOUR',
SUM(TE.TOTAL_TTC) AS 'CA TTC',
ME.LIBELLE AS 'LIBELLE'
FROM TICKET TE
INNER JOIN MODE_REGLEMENT ME ON ME.CODE = TE.MODE_REGLEMENT
GROUP BY TE.DATE, ME.LIBELLE
)
SELECT
[JOUR],
[CA TTC] =
SUM(CASE WHEN [LIBELLE] = 'CREDIT CARD' THEN [CA TTC] ELSE 0 END) +
SUM(CASE WHEN [LIBELLE] = 'CHECK' THEN [CA TTC] ELSE 0 END) +
SUM(CASE WHEN [LIBELLE] = 'SPECIES' THEN [CA TTC] ELSE 0 END),
[CREDIT CARD] = SUM(CASE WHEN [LIBELLE] = 'CREDIT CARD' THEN [CA TTC] ELSE 0 END),
[CHECK] = SUM(CASE WHEN [LIBELLE] = 'CHECK' THEN [CA TTC] ELSE 0 END),
[SPECIES] = SUM(CASE WHEN [LIBELLE] = 'SPECIES' THEN [CA TTC] ELSE 0 END)
FROM CTE
GROUP BY [JOUR]