SQL error message - Incorrect syntax near ')' - sql-server

I get this error message
"Incorrect syntax near ')'."
from the sum(PayHours) line and I would appreciate a bit of guidance on how to go about solving it. I am stuck.
[#PremierThree] from code below is a temporary table being created on the fly and drop afterwards
SELECT *
FROM [#PremierThree]
PIVOT
(SUM(PayHours)
FOR [Pay_ClassHrs] IN ([PBS_Hrs], [POT_Hrs], [PED_Hrs], [POR_Hrs], [Agency_Hrs], [PWH_Hrs], [Sick_Hrs], [PTO_Hrs], [Holiday_Hrs], [PJB_Hrs], [Bugeted_Work_Hrs], [Bugeted_Benefit_Hrs])
) AS pvt1
PIVOT
(SUM(PayAmount)
FOR [Pay_Class$] in ([PBS_$], [POT_$], [PED_$], [POR_$], [Agency_$], [PWH_$], [Sick_$], [PTO_$], [Holiday_$], [PJB_$], [PNH_$],[Bugeted_Work_$], [Bugeted_Benefit_$])
) AS pvt2
ORDER BY
[Facility], CAST([Job_Code] AS INT)

A pivot query does not contain 2 or more pivot clauses in T-SQL see FROM - Using PIVOT and UNPIVOT
You are attempting to output Hours and Dollars as "2 column sets" and frankly I find the T-SQL implementation of pivot too limiting for that. You could try an approach of using unpivot and pivot together to get the effect you want (example here).
Personally I would go for a more traditional style of pivot query that simply uses GROUP BY and case expressions as necessary (the style we always had to use before "pivot was added to SQL at all). e.g. (but I leave the column aliases up to you)
SELECT
[Facility]
, [Job_Code]
, SUM(CASE WHEN Pay_ClassHrs = 'PBS_Hrs' THEN Pay_ClassHrs END) AS x
, SUM(CASE WHEN Pay_ClassHrs = 'POT_Hrs' THEN Pay_ClassHrs END) AS x
, SUM(CASE WHEN Pay_ClassHrs = 'PED_Hrs' THEN Pay_ClassHrs END) AS x
, SUM(CASE WHEN Pay_ClassHrs = 'POR_Hrs' THEN Pay_ClassHrs END) AS x
, SUM(CASE WHEN Pay_ClassHrs = 'Agency_Hrs' THEN Pay_ClassHrs END) AS x
, SUM(CASE WHEN Pay_ClassHrs = 'PWH_Hrs' THEN Pay_ClassHrs END) AS x
, SUM(CASE WHEN Pay_ClassHrs = 'Sick_Hrs' THEN Pay_ClassHrs END) AS x
, SUM(CASE WHEN Pay_ClassHrs = 'PTO_Hrs' THEN Pay_ClassHrs END) AS x
, SUM(CASE WHEN Pay_ClassHrs = 'Holiday_Hrs' THEN Pay_ClassHrs END) AS x
, SUM(CASE WHEN Pay_ClassHrs = 'PJB_Hrs' THEN Pay_ClassHrs END) AS x
, SUM(CASE WHEN Pay_ClassHrs = 'Bugeted_Work_Hrs' THEN Pay_ClassHrs END) AS x
, SUM(CASE WHEN Pay_ClassHrs = 'Bugeted_Benefit_Hrs' THEN Pay_ClassHrs END) AS x
, SUM(CASE WHEN Pay_Class$ = 'POT_$' THEN Pay_Class$ END) AS x
, SUM(CASE WHEN Pay_Class$ = 'PED_$' THEN Pay_Class$ END) AS x
, SUM(CASE WHEN Pay_Class$ = 'POR_$' THEN Pay_Class$ END) AS x
, SUM(CASE WHEN Pay_Class$ = 'Agency_$' THEN Pay_Class$ END) AS x
, SUM(CASE WHEN Pay_Class$ = 'PWH_$' THEN Pay_Class$ END) AS x
, SUM(CASE WHEN Pay_Class$ = 'Sick_$' THEN Pay_Class$ END) AS x
, SUM(CASE WHEN Pay_Class$ = 'PTO_$' THEN Pay_Class$ END) AS x
, SUM(CASE WHEN Pay_Class$ = 'Holiday_$' THEN Pay_Class$ END) AS x
, SUM(CASE WHEN Pay_Class$ = 'PJB_$' THEN Pay_Class$ END) AS x
, SUM(CASE WHEN Pay_Class$ = 'PNH_$' THEN Pay_Class$ END) AS x
, SUM(CASE WHEN Pay_Class$ = 'Bugeted_Work_$' THEN Pay_Class$ END) AS x
, SUM(CASE WHEN Pay_Class$ = 'Bugeted_Benefit_$' THEN Pay_Class$ END) AS x
FROM [#PremierThree]
GROUP BY
[Facility]
, [Job_Code]
UNTESTED!
If the above approach looks too old hat and wordy for you. Try combining the 2 pivots using a join, below I have assumed it would need a full outer join but it might work with a simpler inner join if both subqueries produce the same rows (which is quite likely in your case using that temp table).
SELECT
COALESCE(p1.Facility,p2.Facility) Facility
, COALESCE(p1.Job_Code,p2.Job_Code) Job_Code
, [PBS_Hrs], [POT_Hrs], [PED_Hrs], [POR_Hrs], [Agency_Hrs], [PWH_Hrs], [Sick_Hrs], [PTO_Hrs], [Holiday_Hrs], [PJB_Hrs], [Bugeted_Work_Hrs], [Bugeted_Benefit_Hrs]
, [PBS_$], [POT_$], [PED_$], [POR_$], [Agency_$], [PWH_$], [Sick_$], [PTO_$], [Holiday_$], [PJB_$], [PNH_$],[Bugeted_Work_$], [Bugeted_Benefit_$]
FROM (
SELECT
[Facility]
, [Job_Code]
, [PBS_Hrs], [POT_Hrs], [PED_Hrs], [POR_Hrs], [Agency_Hrs], [PWH_Hrs], [Sick_Hrs], [PTO_Hrs], [Holiday_Hrs], [PJB_Hrs], [Bugeted_Work_Hrs], [Bugeted_Benefit_Hrs]
FROM [#PremierThree]
PIVOT
(SUM(PayHours)
FOR [Pay_ClassHrs] IN ([PBS_Hrs], [POT_Hrs], [PED_Hrs], [POR_Hrs], [Agency_Hrs], [PWH_Hrs], [Sick_Hrs], [PTO_Hrs], [Holiday_Hrs], [PJB_Hrs], [Bugeted_Work_Hrs], [Bugeted_Benefit_Hrs])
) AS pvt1
) AS p1
FULL OUTER JOIN (
SELECT
[Facility]
, [Job_Code]
, [PBS_$], [POT_$], [PED_$], [POR_$], [Agency_$], [PWH_$], [Sick_$], [PTO_$], [Holiday_$], [PJB_$], [PNH_$],[Bugeted_Work_$], [Bugeted_Benefit_$]
PIVOT
(SUM(PayAmount)
FOR [Pay_Class$] in ([PBS_$], [POT_$], [PED_$], [POR_$], [Agency_$], [PWH_$], [Sick_$], [PTO_$], [Holiday_$], [PJB_$], [PNH_$],[Bugeted_Work_$], [Bugeted_Benefit_$])
) AS pvt2
) AS p2
ON p1.Facility = p2.Facility AND p1.Job_Code = p2.Job_Code
ORDER BY
[Facility], CAST([Job_Code] AS INT)
;
For T-SQL: Personally, even with a join approach I don't see any advantage to using pivot when it starts to get complex.

Related

Optimize query with nested inner query and case statements

I have below query written by someone(Database is Microsoft SQL server 2017). I do not have access to database to create indexes etc., So only way I can do is optimize below query as efficient as possible.
My query here is,
Can I use Case and WHEN in inner query as used in the below query? Also am currently trying to remove nested queries by using inner join.
Any other ideas will be appreciated for the below queries. I am not asking to give final optimized query, but asking suggestion specific to below query.
WITH ChildPremiumCTE (COVER_PREMIUM_SET_ID,POLICY_ID, ADDRESS_ID, STATUS_CODE,COVER_PREMIUM_MODEL_ID, SUB_PRODUCT_REF
, COVER_PREMIUM_MODEL_REF, DESCRIPTION, PREMIUM_LEVEL_CODE
, PREMIUM_PAYABLE, PREMIUM_DUE, COMMISSION_GST, COMMISSION, COMMISSION_TOTAL,TERRORISM_GST
, TERRORISM_RI, STAMP_DUTY, GST, FSL
, MODIFIED_PREMIUM, TECHNICAL_PREMIUM, BASE_PREMIUM
, PREMIUM_PAYABLE_TERM, PREMIUM_DUE_TERM, COMMISSION_GST_TERM
, COMMISSION_TERM, COMMISSION_TOTAL_TERM, TERRORISM_GST_TERM
, TERRORISM_RI_TERM, STAMP_DUTY_TERM, GST_TERM, FSL_TERM
, MODIFIED_PREMIUM_TERM, TECHNICAL_PREMIUM_TERM, BASE_PREMIUM_TERM
, PREMIUM_PAYABLE_ANNUALISED, PREMIUM_DUE_ANNUALISED, COMMISSION_GST_ANNUALISED
, COMMISSION_ANNUALISED, COMMISSION_TOTAL_ANNUALISED, TERRORISM_GST_ANNUALISED
, TERRORISM_RI_ANNUALISED, STAMP_DUTY_ANNUALISED, GST_ANNUALISED
, FSL_ANNUALISED, MODIFIED_PREMIUM_ANNUALISED, TECHNICAL_PREMIUM_ANNUALISED
, BASE_PREMIUM_ANNUALISED)
AS (SELECT CPP.COVER_PREMIUM_SET_ID
, CPS.POLICY_ID
, CASE WHEN CPS.PREMIUM_LEVEL_CODE = 'PREMITEM' THEN SS.ADDRESS_ID ELSE AD.ADDRESS_ID END ADDRESS_ID
, SS.STATUS_CODE
, COALESCE(CPM.COVER_PREMIUM_MODEL_ID, 0) COVER_PREMIUM_MODEL_ID
, CASE WHEN CPS.PREMIUM_LEVEL_CODE = 'POLSUM' THEN 'POLICY_SUMMARY'
ELSE CASE WHEN CPS.PREMIUM_LEVEL_CODE = 'SITSUM' THEN 'SITUATION_SUMMARY' ELSE CPS.SUB_PRODUCT_REF END END SUB_PRODUCT_REF
, CPS.COVER_PREMIUM_MODEL_REF
, CPS.DESCRIPTION
, CPS.PREMIUM_LEVEL_CODE
, MAX(CASE WHEN CPP.PREMIUM_MODEL_PART_REF = 'PREMIUM_PAYABLE' THEN CPP.TRANSACTION_AMOUNT END) PREMIUM_PAYABLE
, MAX(CASE WHEN CPP.PREMIUM_MODEL_PART_REF = 'PREMIUM_DUE' THEN CPP.TRANSACTION_AMOUNT END) PREMIUM_DUE
, MAX(CASE WHEN CPP.PREMIUM_MODEL_PART_REF = 'COMMISSION_GST' THEN CPP.TRANSACTION_AMOUNT END) COMMISSION_GST
, MAX(CASE WHEN CPP.PREMIUM_MODEL_PART_REF = 'COMMISSION' THEN CPP.TRANSACTION_AMOUNT END) COMMISSION
, MAX(CASE WHEN CPP.PREMIUM_MODEL_PART_REF = 'COMMISSION_TOTAL' THEN CPP.TRANSACTION_AMOUNT END) COMMISSION_TOTAL
, MAX(CASE WHEN CPP.PREMIUM_MODEL_PART_REF = 'TERRORISM_GST' THEN CPP.TRANSACTION_AMOUNT END) TERRORISM_GST
, MAX(CASE WHEN CPP.PREMIUM_MODEL_PART_REF = 'TERRORISM_RI' THEN CPP.TRANSACTION_AMOUNT END) TERRORISM_RI
, MAX(CASE WHEN CPP.PREMIUM_MODEL_PART_REF = 'STAMP_DUTY' THEN CPP.TRANSACTION_AMOUNT END) STAMP_DUTY
, MAX(CASE WHEN CPP.PREMIUM_MODEL_PART_REF = 'GST' THEN CPP.TRANSACTION_AMOUNT END) GST
, MAX(CASE WHEN CPP.PREMIUM_MODEL_PART_REF = 'FSL' THEN CPP.TRANSACTION_AMOUNT END) FSL
, MAX(CASE WHEN CPP.PREMIUM_MODEL_PART_REF = 'MODIFIED_PREMIUM' THEN CPP.TRANSACTION_AMOUNT END) MODIFIED_PREMIUM
, MAX(CASE WHEN CPP.PREMIUM_MODEL_PART_REF = 'TECHNICAL_PREMIUM' THEN CPP.TRANSACTION_AMOUNT END) TECHNICAL_PREMIUM
, MAX(CASE WHEN CPP.PREMIUM_MODEL_PART_REF = 'BASE_PREMIUM' THEN CPP.TRANSACTION_AMOUNT END) BASE_PREMIUM
, MAX(CASE WHEN CPP.PREMIUM_MODEL_PART_REF = 'PREMIUM_PAYABLE' THEN CPP.TERM_AMOUNT END) PREMIUM_PAYABLE_TERM
, MAX(CASE WHEN CPP.PREMIUM_MODEL_PART_REF = 'PREMIUM_DUE' THEN CPP.TERM_AMOUNT END) PREMIUM_DUE_TERM
, MAX(CASE WHEN CPP.PREMIUM_MODEL_PART_REF = 'COMMISSION_GST' THEN CPP.TERM_AMOUNT END) COMMISSION_GST_TERM
, MAX(CASE WHEN CPP.PREMIUM_MODEL_PART_REF = 'COMMISSION' THEN CPP.TERM_AMOUNT END) COMMISSION_TERM
, MAX(CASE WHEN CPP.PREMIUM_MODEL_PART_REF = 'COMMISSION_TOTAL' THEN CPP.TERM_AMOUNT END) COMMISSION_TOTAL_TERM
, MAX(CASE WHEN CPP.PREMIUM_MODEL_PART_REF = 'TERRORISM_GST' THEN CPP.TERM_AMOUNT END) TERRORISM_GST_TERM
, MAX(CASE WHEN CPP.PREMIUM_MODEL_PART_REF = 'TERRORISM_RI' THEN CPP.TERM_AMOUNT END) TERRORISM_RI_TERM
, MAX(CASE WHEN CPP.PREMIUM_MODEL_PART_REF = 'STAMP_DUTY' THEN CPP.TERM_AMOUNT END) STAMP_DUTY_TERM
, MAX(CASE WHEN CPP.PREMIUM_MODEL_PART_REF = 'GST' THEN CPP.TERM_AMOUNT END) GST_TERM
, MAX(CASE WHEN CPP.PREMIUM_MODEL_PART_REF = 'FSL' THEN CPP.TERM_AMOUNT END) FSL_TERM
, MAX(CASE WHEN CPP.PREMIUM_MODEL_PART_REF = 'MODIFIED_PREMIUM' THEN CPP.TERM_AMOUNT END) MODIFIED_PREMIUM_TERM
, MAX(CASE WHEN CPP.PREMIUM_MODEL_PART_REF = 'TECHNICAL_PREMIUM' THEN CPP.TERM_AMOUNT END) TECHNICAL_PREMIUM_TERM
, MAX(CASE WHEN CPP.PREMIUM_MODEL_PART_REF = 'BASE_PREMIUM' THEN CPP.TERM_AMOUNT END) BASE_PREMIUM_TERM
, MAX(CASE WHEN CPP.PREMIUM_MODEL_PART_REF = 'PREMIUM_PAYABLE' THEN CPP.FUTURE_ANNUALISED_AMOUNT END) PREMIUM_PAYABLE_ANNUALISED
, MAX(CASE WHEN CPP.PREMIUM_MODEL_PART_REF = 'PREMIUM_DUE' THEN CPP.FUTURE_ANNUALISED_AMOUNT END) PREMIUM_DUE_ANNUALISED
, MAX(CASE WHEN CPP.PREMIUM_MODEL_PART_REF = 'COMMISSION_GST' THEN CPP.FUTURE_ANNUALISED_AMOUNT END) COMMISSION_GST_ANNUALISED
, MAX(CASE WHEN CPP.PREMIUM_MODEL_PART_REF = 'COMMISSION' THEN CPP.FUTURE_ANNUALISED_AMOUNT END) COMMISSION_ANNUALISED
, MAX(CASE WHEN CPP.PREMIUM_MODEL_PART_REF = 'COMMISSION_TOTAL' THEN CPP.FUTURE_ANNUALISED_AMOUNT END) COMMISSION_TOTAL_ANNUALISED
, MAX(CASE WHEN CPP.PREMIUM_MODEL_PART_REF = 'TERRORISM_GST' THEN CPP.FUTURE_ANNUALISED_AMOUNT END) TERRORISM_GST_ANNUALISED
, MAX(CASE WHEN CPP.PREMIUM_MODEL_PART_REF = 'TERRORISM_RI' THEN CPP.FUTURE_ANNUALISED_AMOUNT END) TERRORISM_RI_ANNUALISED
, MAX(CASE WHEN CPP.PREMIUM_MODEL_PART_REF = 'STAMP_DUTY' THEN CPP.FUTURE_ANNUALISED_AMOUNT END) STAMP_DUTY_ANNUALISED
, MAX(CASE WHEN CPP.PREMIUM_MODEL_PART_REF = 'GST' THEN CPP.FUTURE_ANNUALISED_AMOUNT END) GST_ANNUALISED
, MAX(CASE WHEN CPP.PREMIUM_MODEL_PART_REF = 'FSL' THEN CPP.FUTURE_ANNUALISED_AMOUNT END) FSL_ANNUALISED
, MAX(CASE WHEN CPP.PREMIUM_MODEL_PART_REF = 'MODIFIED_PREMIUM' THEN CPP.FUTURE_ANNUALISED_AMOUNT END) MODIFIED_PREMIUM_ANNUALISED
, MAX(CASE WHEN CPP.PREMIUM_MODEL_PART_REF = 'TECHNICAL_PREMIUM' THEN CPP.FUTURE_ANNUALISED_AMOUNT END) TECHNICAL_PREMIUM_ANNUALISED
, MAX(CASE WHEN CPP.PREMIUM_MODEL_PART_REF = 'BASE_PREMIUM' THEN CPP.FUTURE_ANNUALISED_AMOUNT END) BASE_PREMIUM_ANNUALISED
FROM COVER_PREMIUM_SET As CPS
LEFT JOIN SITUATION_SECTION As SS ON CPS.POLICY_ID = SS.POLICY_ID
AND CPS.SITUATION_SECTION_REF = SS.SITUATION_SECTION_REF
LEFT JOIN COVER_PREMIUM_PART As CPP ON CPS.COVER_PREMIUM_SET_ID = CPP.COVER_PREMIUM_SET_ID
LEFT JOIN ADDRESS As AD ON CPS.POLICY_ID = AD.POLICY_ID
AND AD.ADDRESS_REF = CPS.ENTITY_INSTANCE_REF
AND CPS.PREMIUM_LEVEL_CODE IN ('SITSUM', 'SUBPRODSUM')
LEFT JOIN COVER_PREMIUM_MODEL As CPM ON CPS.COVER_PREMIUM_MODEL_REF = CPM.COVER_PREMIUM_MODEL_REF
GROUP BY CPP.COVER_PREMIUM_SET_ID,
CPS.POLICY_ID,
CPS.DESCRIPTION,
CPS.PREMIUM_LEVEL_CODE,
CPS.COVER_PREMIUM_MODEL_REF,
CPS.SUB_PRODUCT_REF,
CPM.COVER_PREMIUM_MODEL_ID,
SS.SITUATION_SECTION_ID,
SS.ADDRESS_ID,
SS.STATUS_CODE,
CPS.ENTITY_INSTANCE_REF,
AD.ADDRESS_ID )
select * from (SELECT
0 AS COVER_PREMIUM_SET_ID
, a1.POLICY_ID
, a1.ADDRESS_ID
, a1.STATUS_CODE
, CPM_CHILD.PARENT_ID AS COVER_PREMIUM_MODEL_ID
, CASE WHEN CPM.PREMIUM_LEVEL_CODE = 'POLSUM' THEN 'POLICY_SUMMARY'
ELSE CASE WHEN CPM.PREMIUM_LEVEL_CODE = 'SITSUM' THEN 'SITUATION_SUMMARY' ELSE a1.SUB_PRODUCT_REF END END SUB_PRODUCT_REF
, CPM.COVER_PREMIUM_MODEL_REF
, CPM.NAME AS Description
, CPM.PREMIUM_LEVEL_CODE AS PREMIUM_LEVEL_CODE
, sum(a1.PREMIUM_PAYABLE) PREMIUM_PAYABLE
, sum(a1.PREMIUM_DUE) PREMIUM_DUE
, sum(a1.COMMISSION_GST) COMMISSION_GST
, sum(a1.COMMISSION) COMMISSION
, sum(a1.COMMISSION_TOTAL) COMMISSION_TOTAL,sum(a1.TERRORISM_GST) TERRORISM_GST
, sum(a1.TERRORISM_RI) TERRORISM_RI, sum(a1.STAMP_DUTY) STAMP_DUTY,sum(a1.GST ) GST, sum(a1.FSL ) FSL
, sum(a1.MODIFIED_PREMIUM ) MODIFIED_PREMIUM, sum(a1.TECHNICAL_PREMIUM ) TECHNICAL_PREMIUM, sum(a1.BASE_PREMIUM ) BASE_PREMIUM
, sum(a1.PREMIUM_PAYABLE_TERM) PREMIUM_PAYABLE_TERM, sum(a1.PREMIUM_DUE_TERM ) PREMIUM_DUE_TERM
, sum(a1.COMMISSION_GST_TERM ) COMMISSION_GST_TERM, sum(a1.COMMISSION_TERM ) COMMISSION_TERM
, sum(a1.COMMISSION_TOTAL_TERM ) COMMISSION_TOTAL_TERM, sum(a1.TERRORISM_GST_TERM ) TERRORISM_GST_TERM
, sum(a1.TERRORISM_RI_TERM ) TERRORISM_RI_TERM, sum(a1.STAMP_DUTY_TERM ) STAMP_DUTY_TERM
, sum(a1.GST_TERM ) GST_TERM, sum(a1.FSL_TERM ) FSL_TERM, sum(a1.MODIFIED_PREMIUM_TERM ) MODIFIED_PREMIUM_TERM
, sum(a1.TECHNICAL_PREMIUM_TERM ) TECHNICAL_PREMIUM_TERM, sum(a1.BASE_PREMIUM_TERM ) BASE_PREMIUM_TERM
, sum(a1.PREMIUM_PAYABLE_ANNUALISED) PREMIUM_PAYABLE_ANNUALISED, sum(a1.PREMIUM_DUE_ANNUALISED ) PREMIUM_DUE_ANNUALISED
, sum(a1.COMMISSION_GST_ANNUALISED ) COMMISSION_GST_ANNUALISED, sum(a1. COMMISSION_ANNUALISED ) COMMISSION_ANNUALISED
, sum(a1. COMMISSION_TOTAL_ANNUALISED ) COMMISSION_TOTAL_ANNUALISED, sum(a1.TERRORISM_GST_ANNUALISED ) TERRORISM_GST_ANNUALISED
, sum(a1.TERRORISM_RI_ANNUALISED ) TERRORISM_RI_ANNUALISED, sum(a1.STAMP_DUTY_ANNUALISED ) STAMP_DUTY_ANNUALISED
, sum(a1.GST_ANNUALISED ) GST_ANNUALISED, sum(a1.FSL_ANNUALISED ) FSL_ANNUALISED
, sum(a1.MODIFIED_PREMIUM_ANNUALISED ) MODIFIED_PREMIUM_ANNUALISED
, sum(a1.TECHNICAL_PREMIUM_ANNUALISED ) TECHNICAL_PREMIUM_ANNUALISED
, sum(a1.BASE_PREMIUM_ANNUALISED) BASE_PREMIUM_ANNUALISED
FROM COVER_PREMIUM_MODEL CPM,
COVER_PREMIUM_MODEL CPM_CHILD,
ChildPremiumCTE a1
WHERE
CPM.PREMIUM_LEVEL_CODE = 'PREMRLUP'
AND CPM_CHILD.PARENT_ID = CPM.COVER_PREMIUM_MODEL_ID
AND CPM_CHILD.COVER_PREMIUM_MODEL_REF = a1.COVER_PREMIUM_MODEL_REF
GROUP BY
a1.POLICY_ID,
a1.ADDRESS_ID,
CPM_CHILD.PARENT_ID,
CPM.NAME,
CPM.PREMIUM_LEVEL_CODE,
a1.SUB_PRODUCT_REF,
CPM.COVER_PREMIUM_MODEL_REF,
a1.STATUS_CODE
UNION ALL
select * from ChildPremiumCTE) CoverPremium where CoverPremium.POLICY_ID = 77780029
So far what I have improved is,
Made union to union all
Trying to convert subqueries into where clause
built in functions like MAX, SUM to like string literal
First suggestion is same as #LukStorms.Also always use alias of table and prefix them in column so that it is very easy to understand and debug.
Can I use Case and WHEN in inner query as used in the below query?
Everything has cost.It seem that in this case cost is negligible.
Any other ideas will be appreciated for the below queries. I am not
asking to give final optimized query, but asking suggestion specific
to below query.
GROUP BY on All column is always bad idea.First Using CTE or #Temp table
write Group By query using only require table and Group By on Key column only.
Suppose you need some other column also which is not part of aggregate or Group By,then no problem don't try to use that column here.
Join the same table in main query to get those columns which is not part of aggregate.
Then in Main query again join that CTE or temp table with other table.
This is how you should design your query .
PREMIUM_MODEL_PART_REF and TRANSACTION_AMOUNT belong to which table ?
Table COVER_PREMIUM_MODEL are use 3 times in query.Put the require data of COVER_PREMIUM_MODEL on #temp table .There must be some common result in all three join.
Excerpt
select * from (Select * blah blah
UNION ALL
select * from ChildPremiumCTE) a2 where a2.POLICY_ID = 77780029
WHY use where POLICY_ID = 77780029 in the end ?
This way first so many rows will be process in inner query then finally reduce to POLICY_ID = 77780029.
So WHY not use POLICY_ID = 77780029 in inner query somewhere in the first place.
built in functions like MAX, SUM to like string literal
It depend what type of UDF it is and what you have written in it.
In short UDF are notoriously Bad Perform-ant most of the time.
It do not appear to be that MAX, SUM need UDF.

PIvot with multiple result values

im trying to put multiple sums in this pivot table but i havent been succeful,
This is the Raw data
from
select
billname,
orderperiodyear,
Sum_buyprice,
Sum_Sellprice,
Tonnage
From Sum_Orders
This is my pivot how can i include buy price and tonnage in the pivot results
SELECT billname,SUM([2017])AS '2017', SUM([2016]) AS '2016'
FROM Sum_Orders
PIVOT
(
SUM(Sum_SellPrice)
FOR OrderperiodYear IN ([2017],[2016])
)AS pvt
WHERE OrderStatus IN ('Complete', 'Invoiced')
AND ( (MONTH(OrderDate) = MONTH(GETDATE()) AND day(OrderDate) <= DAY(GETDATE()))
OR MONTH(OrderDate) < MONTH(GETDATE()))
Group by BILLNAME
HAVING COALESCE(SUM([2017]), SUM([2016])) IS NOT NULL
ORDER BY BILLNAME ASC
This is what i get from my pivot
Im looking for something like this
You first have to do unpivot first DEMO
SELECT billname,
CAST([OrderperiodYear] as varchar(500)) + '_' + CAST([attribute] as varchar(500)) as attribute,
[data]
FROM (SELECT billname,
[OrderperiodYear],
[Sum_Buyprice] as Buy,
[Sum_Sellprice] as Sell,
[Tonnage] as Ton
FROM records) p
UNPIVOT
([data] FOR [attribute] IN
(Buy, Sell, Ton)
) as unpvt
OUTPUT
Then you can create a Dynamic Pivot.
One option is to skip pivot() and go for the old style cross tab.
select
billname
, [2016_buyprice] = sum(case when OrderPeriodYear = 2016 then sum_buyprice else null end)
, [2017_buyprice] = sum(case when OrderPeriodYear = 2017 then sum_buyprice else null end)
, [2016_sellprice] = sum(case when OrderPeriodYear = 2016 then sum_sellprice else null end)
, [2017_sellprice] = sum(case when OrderPeriodYear = 2017 then sum_sellprice else null end)
, [2016_tonnage] = sum(case when OrderPeriodYear = 2016 then tonnage else null end)
, [2017_tonnage] = sum(case when OrderPeriodYear = 2017 then tonnage else null end)
from sum_orders
where OrderStatus in ('Complete', 'Invoiced')
and ((month(OrderDate) = month(getdate())
and day(OrderDate) <= day(getdate()))
or month(OrderDate) < month(getdate()))
group by billname
order by billname asc

SQL query SUM() AND GROUP BY for 2 columns in a table

I am using Microsoft Sql Server management studio.
I have had mixed success creating a tax report for a particular type of invoice that I have.
I have amounts under 6%, other amounts under 13.5% and the last amount has a complete total of both 6% and 13.5%.
I have got my answer in the results, but two different rows for each invoice are displayed. One is for 6% values and the other for 13.5% values.
I need to somehow merge these two rows into one single row for each invoice.
My Sql query is as follows:
SELECT tran_no ,
tran_date ,
( SELECT SUM(edetail_amt)
WHERE edetail_taxid = '6008U_='
) AS '6% amt' ,
( SELECT SUM(edetail_per)
WHERE edetail_taxid = '6008U_='
) AS '6% vat' ,
( SELECT SUM(edetail_amt)
WHERE edetail_taxid = '6008U_>'
) AS '13.5% amt' ,
( SELECT SUM(edetail_per)
WHERE edetail_taxid = '6008U_>'
) AS '13.5% vat' ,
( SELECT SUM(edetail_amt + edetail_per)
WHERE edetail_taxid IN ( '6008U_=', '6008U_>' )
) AS 'Net Total'
FROM h_edetail
INNER JOIN h_tran ON edetail_tranid = tran_kid
WHERE tran_trantype = 'PI'
AND tran_date = '2016-11-03 00:00:00.000'
GROUP BY tran_no ,
tran_date ,
edetail_taxid
ORDER BY tran_no;
A screenshot of the query along with the results are as follows:
If am not wrong you are looking for this
SELECT tran_no,
tran_date,
Sum(case when edetail_taxid = '6008U_=' then edetail_amt else 0 end) AS '6% amt',
Sum(case when edetail_taxid = '6008U_=' then edetail_per else 0 end) AS '6% vat',
Sum(case when edetail_taxid = '6008U_>' then edetail_amt else 0 end) AS '13.5% amt',
Sum(case when edetail_taxid = '6008U_>' then edetail_per else 0 end) AS '13.5% vat',
Sum(case when edetail_taxid IN ( '6008U_=', '6008U_>' ) then edetail_amt + edetail_per else 0 end) AS 'Net Total'
FROM h_edetail
INNER JOIN h_tran
ON edetail_tranid = tran_kid
WHERE tran_trantype = 'PI'
AND tran_date = '2016-11-03 00:00:00.000'
GROUP BY tran_no,
tran_date
ORDER BY tran_no
Because of select sum(edetail_amt) where edetail_taxid='6008U_=' you are forced to add edetail_taxid in group by that is the reason for duplicate records. You can do that by adding case inside SUM aggregate

Need to add a subquery in a CASE expression that is part of an aggregate function

I need to add the number of records in which the status is set to 'reopened'. But the 'reopened' status has several IDs.
This is the subquery that will Id the 'reopen' statuses:
SELECT (CASE WHEN s.sr_status_recid = 1 THEN 1 ELSE 0 END) AS Reopened
from v_rpt_service s
where vsrv.sr_status_recid in
(select distinct SR_Status_RecID from SR_Status where [Description] like '%Re-opened%'))
This is the main query that the above query needs to be a part:
SELECT DATEPART(WK, vsrv.date_entered) as WkNumber,
COUNT(vsrv.TicketNbr) AS OpenedIssues, --total ticket count
SUM(CASE WHEN vsrv.Closed_Flag = 1 THEN 1 ELSE 0 END) AS ClosedIssues, --sum of tickets with closed_flag = 1
(SELECT SUM(CASE WHEN s.sr_status_recid = 1 THEN 1 ELSE 0 END)
from v_rpt_service s
where vsrv.sr_status_recid in
(select distinct SR_Status_RecID from SR_Status where [Description] like '%Re-opened%')) AS ReopenedIssues,
SUM(CASE WHEN vsrvy.Surveys_Completed = 1 THEN 1 ELSE 0 END) AS SurveysCompletedWithConnectWise, -- Surveys_Completed flag in view is 1
SUM(CASE WHEN Source = 'Portal' THEN 1 ELSE 0 END) AS IssueLoggedPortal,
SUM(CASE WHEN Source = 'Email Connector' THEN 1 ELSE 0 END) AS IssueLoggedEmai
FROM v_rpt_service vsrv LEFT OUTER JOIN v_rpt_SurveysByTicket vsrvy ON vsrv.TicketNbr = Vsrvy.SR_Service_RecID
WHERE vsrv.company_name <> 'XYZ Test Company' AND vsrv.date_entered BETWEEN '01/01/2016' AND '10/07/2016'
GROUP BY DATEPART(WK, vsrv.date_entered)
ORDER BY WkNumber
How can I have a subquery that uses a CASE statement and the CASE statement is aggregated?
You can use CROSS APPLY
SELECT DATEPART(WK, vsrv.date_entered) as WkNumber,
COUNT(vsrv.TicketNbr) AS OpenedIssues, --total ticket count
SUM(CASE WHEN vsrv.Closed_Flag = 1 THEN 1 ELSE 0 END) AS ClosedIssues, --sum of tickets with closed_flag = 1
SUM(CountReopen.YesNo) AS NumberOfReopen,
SUM(CASE WHEN vsrvy.Surveys_Completed = 1 THEN 1 ELSE 0 END) AS SurveysCompletedWithConnectWise, -- Surveys_Completed flag in view is 1
SUM(CASE WHEN Source = 'Portal' THEN 1 ELSE 0 END) AS IssueLoggedPortal,
SUM(CASE WHEN Source = 'Email Connector' THEN 1 ELSE 0 END) AS IssueLoggedEmail
FROM v_rpt_service vsrv
LEFT OUTER JOIN v_rpt_SurveysByTicket vsrvy
ON vsrv.TicketNbr = Vsrvy.SR_Service_RecID
CROSS APPLY (
SELECT IIF(COUNT(*) > 0,1,0) YesNo
FROM SR_Status
where [Description] like '%Re-opened%'
AND SR_Status_ID = vsrv.sr_status_recid
) CountReopen(YesNo)
WHERE vsrv.company_name <> 'XYZ Test Company'
AND vsrv.date_entered BETWEEN '01/01/2016' AND '10/07/2016'
GROUP BY DATEPART(WK, vsrv.date_entered)
ORDER BY WkNumber

When I SUM values of each month between 2 dates, I get the wrong value

I am really struggling with a query. I want the sum of each month between Aug 2014 and July 2015. If I specify the between dates in the where clause it sums all the months.
Here is my query:
DECLARE #CurrentYear int = DATEpart(year,getdate())
DECLARE #PreviousYear int = DATEpart(year,getdate()) -1
SELECT
SUM(CASE WHEN a.fin_period = concat(#PreviousYear,'08') THEN a.balance ELSE 0 END) AS BalanceAug ,
SUM(CASE WHEN a.fin_period = concat(#PreviousYear,'09') THEN a.balance ELSE 0 END) AS BalanceSep ,
SUM(CASE WHEN a.fin_period = concat(#PreviousYear,'10') THEN a.balance ELSE 0 END) AS BalanceOct ,
SUM(CASE WHEN a.fin_period = concat(#PreviousYear,'11') THEN a.balance ELSE 0 END) AS BalanceNov ,
SUM(CASE WHEN a.fin_period = concat(#PreviousYear,'12') THEN a.balance ELSE 0 END) AS BalanceDec ,
...etc.
FROM subaccount_history a with (nolock)
WHERE fin_period between concat(#PreviousYear,'08') and concat(#CurrentYear,'12')
The issue is with the between clause, i tried group by but that also doesn't work. It sums everything between the 2 dates specified.

Resources