SQL Server : combine query result to one row - sql-server

I want to format the query like this. is it possible?

With conditional aggregation:
SELECT
MAX(CASE WHEN CHECKTYPE = 'I' AND TIMETYPE = 'AM' THEN FORMAT(CHECKTIME, N'HH:mm') END) [AM-IN],
MAX(CASE WHEN CHECKTYPE = 'O' AND TIMETYPE = 'AM' THEN FORMAT(CHECKTIME, N'HH:mm') END) [AM-OUT],
MAX(CASE WHEN CHECKTYPE = 'I' AND TIMETYPE = 'PM' THEN FORMAT(CHECKTIME, N'HH:mm') END) [PM-IN],
MAX(CASE WHEN CHECKTYPE = 'O' AND TIMETYPE = 'PM' THEN FORMAT(CHECKTIME, N'HH:mm') END) [PM-OUT]
FROM [dbo].[CHECKINOUT]
WHERE [USERID] = N'21477' AND [CHECKTIME] BETWEEN N'2020-02-3 00:00:00' AND N'2020-02-4 00:00:00'
GROUP BY [USERID]

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.

Subquery a Cast Function

I have the following code which I'm using to transpose some data (see below); however, when running the code I received a 'Operand data type datetime2 is invalid for sum operator' error, which I believe is due to the fact the [RESULT_DT_TM] column has both date and time values. With the help from the outstanding contributors, I made what turns out to be a very simple code that removes the date from the [RESULT_DT_TM]:
select cast([RESULT_DT_TM] as time (0)) as [result_dt]
from ED_Vitals_Import_Master
I would like to include this code within the main query so I have use the new [result_dt] variable but am having trouble embedding it. Is it possible to do what I am seeking?
Select *
From (
Select a.[PT_FIN]
,B.*
From (Select *,RN=Row_Number() over (Partition By PT_FIN Order by [RESULT_DT_TM]) From ED_Vitals_Import_Master ) A
Cross Apply (values (concat('Time' ,RN),[RESULT_DT_TM])
,(concat('Weight' ,RN),[WEIGHT_RESULT])
,(concat('SysBp' ,RN),[SYSBP_RESULT])
,(concat('DiaBP',RN),[DIABP_RESULT])
,(concat('Temp' ,RN),[TEMPERATURE_RESULT])
,(concat('Oxy' ,RN),[OXYGEN_SAT_RESULT])
,(concat('Fio' ,Rn),[FIO2_RESULT])
) B(Item,Value)
) src
Pivot (sum(Value) for Item in ([RESULT_DT_TM1],[Weight1],[Sysbp1],[DiaBP1], [Temp1], [Oxy1], [Fio1]
,[RESULT_DT_TM2],[Weight2],[Sysbp2],[DiaBP2], [Temp2], [Oxy2], [Fio2]
,[RESULT_DT_TM3],[Weight3],[Sysbp3],[DiaBP3], [Temp3], [Oxy3], [Fio3]
,[RESULT_DT_TM4],[Weight4],[Sysbp4],[DiaBP4], [Temp4], [Oxy4], [Fio4]
) ) pvt
Since you are mixing datatypes... perhaps a conditional aggregation would be more useful.
Example
Select a.[PT_FIN]
,[RESULT_DT_TM1] = max(case when RN=1 then [RESULT_DT_TM] end)
,[Weight1] = max(case when RN=1 then [Weight] end)
,[Sysbp1] = max(case when RN=1 then [Sysbp] end)
,[DiaBP1] = max(case when RN=1 then [DiaBP] end)
,[Temp1] = max(case when RN=1 then [Temp] end)
,[Oxy1] = max(case when RN=1 then [Oxy] end)
,[Fio1] = max(case when RN=1 then [Fio] end)
,[RESULT_DT_TM2] = max(case when RN=2 then [RESULT_DT_TM] end)
,[Weight2] = max(case when RN=2 then [Weight] end)
,[Sysbp2] = max(case when RN=2 then [Sysbp] end)
,[DiaBP2] = max(case when RN=2 then [DiaBP] end)
,[Temp2] = max(case when RN=2 then [Temp] end)
,[Oxy2] = max(case when RN=2 then [Oxy] end)
,[Fio2] = max(case when RN=2 then [Fio] end)
--- Extend the Groups Here ---
From (Select *,RN=Row_Number() over (Partition By PT_FIN Order by [RESULT_DT_TM]) From ED_Vitals_Import_Master ) A
Group By a.[PT_FIN]

Switching rows with columns to generate a summary report in SQL Server

I have this query that geneartes data in format also shown:
SELECT TOP (10)
{ FN CONCAT({ FN CONCAT(dbo.BILL_INFO.BILL_NUMBER, '-')}, REPLICATE('0', 2 - LEN(RTRIM(dbo.BILL_INFO.PAY_MODE_ID)))
+ RTRIM(dbo.BILL_INFO.PAY_MODE_ID))} AS Id,
dbo.BILL_INFO.PAY_MODE_ID,
dbo.MASTER_PAY_MODE.NAME AS PAY_MODE
FROM dbo.BILL_INFO
INNER JOIN dbo.MASTER_PAY_MODE
ON dbo.BILL_INFO.PAY_MODE_ID = dbo.MASTER_PAY_MODE.ID
ORDER BY dbo.BILL_INFO.BILL_DATE DESC;
I need to transpose the result to this format:
I can do this using excel and a pivot but is there a way using SQL query?
Sample Data
Id |BILL_DATE |PAY_MODE
0000056-1002-18-10|2018-11-26 14:03:03.553|Bank Transfer
0001199-1002-18-05|2018-11-26 13:58:25.763|Credit Card
0000162-1030-18-05|2018-11-26 13:55:40.590|Credit Card
0001198-1002-18-05|2018-11-26 13:49:39.013|Credit Card
0001859-1030-18-04|2018-11-26 13:44:23.333|Free
0004443-1002-18-03|2018-11-26 13:42:27.550|Debit
0001532-1031-18-03|2018-11-26 13:36:23.010|Debit
0001916-1002-18-04|2018-11-26 13:33:23.157|Free
0001915-1002-18-04|2018-11-26 13:32:45.653|Free
0001914-1002-18-04|2018-11-26 13:30:35.580|Free
0004442-1002-18-03|2018-11-26 13:24:11.730|Debit
0004441-1002-18-03|2018-11-26 13:22:35.020|Debit
0004440-1002-18-03|2018-11-26 13:12:01.920|Debit
0004439-1002-18-03|2018-11-26 13:10:06.483|Debit
0001197-1002-18-05|2018-11-26 13:07:19.673|Credit Card
0001196-1002-18-05|2018-11-26 13:02:31.527|Credit Card
0004438-1002-18-03|2018-11-26 13:00:01.000|Debit
0001003-1030-18-03|2018-11-26 12:57:42.630|Debit
0001531-1031-18-03|2018-11-26 12:56:33.210|Debit
0001913-1002-18-04|2018-11-26 12:54:41.077|Free
Update
I have taken the solution provided by #[Tim Biegeleisen] as follows:
SELECT
MONTH(bi.BILL_DATE) AS [Month],
MAX(CASE WHEN m.NAME = 'Cheque' THEN bi.PAY_MODE_ID END) AS Cheque,
MAX(CASE WHEN m.NAME = 'Cash' THEN bi.PAY_MODE_ID END) AS Cash,
MAX(CASE WHEN m.NAME = 'Bank Transfer' THEN bi.PAY_MODE_ID END) AS [Bank Transfer],
MAX(CASE WHEN m.NAME = 'Credit Card' THEN bi.PAY_MODE_ID END) AS [Credit Card],
MAX(CASE WHEN m.NAME = 'Debit' THEN bi.PAY_MODE_ID END) AS Debit,
MAX(CASE WHEN m.NAME = 'Free' THEN bi.PAY_MODE_ID END) AS Free
FROM dbo.BILL_INFO bi
INNER JOIN dbo.MASTER_PAY_MODE m
ON bi.PAY_MODE_ID = m.ID
WHERE YEAR(bi.BILL_DATE) = 2018
GROUP BY
MONTH(bi.BILL_DATE) ORDER BY MONTH(bi.BILL_DATE)
You may do so via a pivot query, perhaps something alone these lines:
SELECT
YEAR(bi.BILL_DATE) + '-' + MONTH(bi.BILL_DATE) AS Date,
COUNT(CASE WHEN m.NAME = 'Cheque' THEN 1 END) AS Cheque,
COUNT(CASE WHEN m.NAME = 'Cash' THEN 1 END) AS Cash,
COUNT(CASE WHEN m.NAME = 'Bank Transfer' THEN 1 END) AS [Bank Transfer],
COUNT(CASE WHEN m.NAME = 'Credit Card' THEN 1 END) AS [Credit Card],
COUNT(CASE WHEN m.NAME = 'Debit' THEN 1 END) AS Debit,
COUNT(CASE WHEN m.NAME = 'Free' THEN 1 END) AS Free
FROM dbo.BILL_INFO bi
INNER JOIN dbo.MASTER_PAY_MODE m
ON bi.PAY_MODE_ID = m.ID
GROUP BY
YEAR(bi.BILL_DATE) + '-' + MONTH(bi.BILL_DATE);
Note that I am grouping the date column by month and year, because a given month appearing in the BILL_INFO table could belong to more than one year, in general.

T-SQL applying pivot for two rows under a single column

On SQL Server 2014 I use the following code:
CREATE TABLE TempTable
(
LType varchar(255),
LStatus varchar(255),
PAmount decimal(16,2),
RAmount decimal(16,2));
INSERT INTO TempTable (LType, LStatus, PAmount, RAmount)
VALUES ('TypeA','StatusA', '1000', '10'),
('TypeB', 'StatusC', '500', '50'),
('TypeC', 'StatusB', '2500', '100'),
('TypeB', 'StatusB', '1000', '50'),
('TypeA', 'StatusA', '3000', '25'),
('TypeC', 'StatusB', '2200', '50');
Select Ltype, Lstatus, SUM(PAmount) as PAmount, SUM(RAmount) as RAmount
From TempTable
Where PAmount > 0
Group By LType, LStatus
to get this table:
What I’m trying to achieve is:
I used pivot but was unable to apply it simultaneously for PAmount and RAmount under Status columns.
Can anyone help with solution?
You can use conditional aggregation for this. This assumes you will always have these values. If you need this to be dynamic then there is a bit more work to do.
select StatusA_PAMount = max(case when Totals.Lstatus = 'StatusA' then Totals.PAmount end)
, StatusA_RAMount = max(case when Totals.Lstatus = 'StatusA' then Totals.RAmount end)
, StatusB_PAMount = max(case when Totals.Lstatus = 'StatusB' then Totals.PAmount end)
, StatusB_RAMount = max(case when Totals.Lstatus = 'StatusB' then Totals.RAmount end)
, StatusC_PAMount = max(case when Totals.Lstatus = 'StatusC' then Totals.PAmount end)
, StatusC_RAMount = max(case when Totals.Lstatus = 'StatusC' then Totals.RAmount end)
from
(
Select Lstatus
, SUM(PAmount) as PAmount
, SUM(RAmount) as RAmount
From TempTable
Where PAmount > 0
Group By LStatus
) Totals

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

Resources