I have a table with three columns and 18 rows.
I want to change into the 18 columns with two rows.
Here is the table
Category Bands Points
20_CAT1 21-22 10
20_CAT2 23-25 20
20_CAT3 26- 30
30_CAT1 31-33 10
30_CAT2 34-38 20
30_CAT3 39- 30
40_CAT1 41-44 5
40_CAT2 45-50 15
40_CAT3 51- 25
50_CAT1 50-55 5
50_CAT2 56-63 15
50_CAT3 64- 25
60_CAT1 61-66 5
60_CAT2 67-75 20
60_CAT3 76- 30
70_CAT1 71-77 5
70_CAT2 78-88 20
70_CAT3 89- 30
The new table should have the "Category" As the Columns with the "Bands" and "Points" as the rows
I'm not sure how to use Cross Apply and Pivot to do this or even if this is the correct approach.
Thanks in advance.
I've managed to get the following to work without the use of a PIVOT.
SELECT
MAX(CASE WHEN Category = '20_CAT1' THEN Bands END) [20_CAT1_Bands],
MAX(CASE WHEN Category = '20_CAT1' THEN Points END) [20_CAT1_Points],
MAX(CASE WHEN Category = '20_CAT2' THEN Bands END) [20_CAT2_Bands],
MAX(CASE WHEN Category = '20_CAT2' THEN Points END) [20_CAT2_Points],
MAX(CASE WHEN Category = '20_CAT3' THEN Bands END) [20_CAT3_Bands],
MAX(CASE WHEN Category = '20_CAT3' THEN Points END) [20_CAT3_Points],
MAX(CASE WHEN Category = '30_CAT1' THEN Bands END) [30_CAT1_Bands],
MAX(CASE WHEN Category = '30_CAT1' THEN Points END) [30_CAT1_Points],
MAX(CASE WHEN Category = '30_CAT2' THEN Bands END) [30_CAT2_Bands],
MAX(CASE WHEN Category = '30_CAT2' THEN Points END) [30_CAT2_Points],
MAX(CASE WHEN Category = '30_CAT3' THEN Bands END) [30_CAT3_Bands],
MAX(CASE WHEN Category = '30_CAT3' THEN Points END) [30_CAT3_Points],
MAX(CASE WHEN Category = '40_CAT1' THEN Bands END) [40_CAT1_Bands],
MAX(CASE WHEN Category = '40_CAT1' THEN Points END) [40_CAT1_Points],
MAX(CASE WHEN Category = '40_CAT2' THEN Bands END) [40_CAT2_Bands],
MAX(CASE WHEN Category = '40_CAT2' THEN Points END) [40_CAT2_Points],
MAX(CASE WHEN Category = '40_CAT3' THEN Bands END) [40_CAT3_Bands],
MAX(CASE WHEN Category = '40_CAT3' THEN Points END) [40_CAT3_Points],
MAX(CASE WHEN Category = '50_CAT1' THEN Bands END) [50_CAT1_Bands],
MAX(CASE WHEN Category = '50_CAT1' THEN Points END) [50_CAT1_Points],
MAX(CASE WHEN Category = '50_CAT2' THEN Bands END) [50_CAT2_Bands],
MAX(CASE WHEN Category = '50_CAT2' THEN Points END) [50_CAT2_Points],
MAX(CASE WHEN Category = '50_CAT3' THEN Bands END) [50_CAT3_Bands],
MAX(CASE WHEN Category = '50_CAT3' THEN Points END) [50_CAT3_Points],
MAX(CASE WHEN Category = '60_CAT1' THEN Bands END) [60_CAT1_Bands],
MAX(CASE WHEN Category = '60_CAT1' THEN Points END) [60_CAT1_Points],
MAX(CASE WHEN Category = '60_CAT2' THEN Bands END) [60_CAT2_Bands],
MAX(CASE WHEN Category = '60_CAT2' THEN Points END) [60_CAT2_Points],
MAX(CASE WHEN Category = '60_CAT3' THEN Bands END) [60_CAT3_Bands],
MAX(CASE WHEN Category = '60_CAT3' THEN Points END) [60_CAT3_Points],
MAX(CASE WHEN Category = '70_CAT1' THEN Bands END) [70_CAT1_Bands],
MAX(CASE WHEN Category = '70_CAT1' THEN Points END) [70_CAT1_Points],
MAX(CASE WHEN Category = '70_CAT2' THEN Bands END) [70_CAT2_Bands],
MAX(CASE WHEN Category = '70_CAT2' THEN Points END) [70_CAT2_Points],
MAX(CASE WHEN Category = '70_CAT3' THEN Bands END) [70_CAT3_Bands],
MAX(CASE WHEN Category = '70_CAT3' THEN Points END) [70_CAT3_Points]
FROM #table
Related
With the help from another poster, I developed the following code:
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_RESULT] end)
,[Sysbp1] = max(case when RN=1 then [SYSBP_RESULT] end)
,[DiaBP1] = max(case when RN=1 then [DIABP_RESULT] end)
,[Temp1] = max(case when RN=1 then [TEMPERATURE_RESULT] end)
,[Oxy1] = max(case when RN=1 then [OXYGEN_SAT_RESULT] end)
,[Fio1] = max(case when RN=1 then [FIO2_RESULT] end)
,[Flow1] = max(case when RN=1 then [Flow_Rate_Result] end)
,[RESULT_DT_TM2] = max(case when RN=1 then [RESULT_DT_TM] end)
,[Weight2] = max(case when RN=1 then [Weight] end)
,[Sysbp2] = max(case when RN=1 then [Sysbp] end)
,[DiaBP2] = max(case when RN=1 then [DiaBP] end)
,[Temp2] = max(case when RN=1 then [TEMPERATURE_RESULT] end)
,[Oxy2] = max(case when RN=1 then [OXYGEN_SAT_RESULT] end)
,[Fio2] = max(case when RN=1 then [FIO2_RESULT] end)
,[Flow2] = max(case when RN=1 then [Flow_Rate_Result] end)
ETC
Each number at the end of the variable corresponds to a row a subject may have data (some subjects have 1 row of data, some may have 10). Is there an efficient way to repeat this code to capture a max of 10 rows of data so I do not have to add for example:
[RESULT_DT_TM3]= max(case when RN=3 then [RESULT_DT_TM] end)
[Weight3]= max(case when RN=3 then [WEIGHT_RESULT] end)
[RESULT_DT_TM4] = max(case when RN=4 then [RESULT_DT_TM] end)
[Weight4]= max(case when RN=4 then [Weight_Result] end)
....
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]
I have this procedure that is returning three records and I need it to only return the row with the max date. I have created a function to pass comma delimited values. It returns multi records for the values being passed. I need it to return only the record with the max date. I think I missing something simple. Thanks in Advance
SELECT DISTINCT
ZITMTSICOD6.LNGDES_0 as variety
,STOLOT.YCROPYR_0 as crop_year
,STOLOT.LOT_0 as lot_number
,ZITMTSICOD2.LNGDES_0 AS product_name
,ISNULL([UV_Alpha], 'NA') as uv_alpha
,ISNULL([UV_Beta], 'NA') as uv_beta
,ISNULL([HSI], 'NA') as hsi
,ISNULL(Moisture, 'NA') as moisture
,ISNULL(Oil_by_Dist,'NA') as oil_by_dist
,ISNULL([HPLC Alpha],'NA') as hplc_alpha
,ISNULL([HPLC Beta],'NA') as hplc_beta
,ISNULL([HPLC Cohumulone],'NA') as hplc_cohumulone
,ISNULL([HPLC Colupulone],'NA') as hplc_colupulone
,ISNULL([Mebak Alpha 7.5],'NA') as mebak_alpha_7_5
,ISNULL([LCV Alpha 7.4],'NA') as lcv_alpha_7_4
,ISNULL(Oil_B_Pinene,'NA') as oil_b_pinene
,ISNULL(Oil_Myrcene,'NA') as oil_myrcene
,ISNULL(Oil_Linalool,'NA') as oil_linalool
,ISNULL(Oil_Caryophyllene,'NA') as oil_caryophyllene
,ISNULL(Oil_Farnesene,'NA') as oil_farnesene
,ISNULL(Oil_Humulene,'NA') as oil_humulene
,ISNULL(Oil_Geraniol,'NA') as oil_geraniol
,STOQLYH.CREDAT_0 as created_at
FROM
LIVE.STOLOT
left outer join
LIVE.STOQLYD on STOLOT.LOT_0 = STOQLYD.LOT_0 and STOLOT.SLO_0 =
STOQLYD.SLO_0 and STOQLYD.ITMREF_0 = STOLOT.ITMREF_0
left outer join
LIVE.STOQLYH on STOQLYH.VCRNUM_0 = STOQLYD.VCRNUM_0 and STOQLYH.ITMREF_0
= STOQLYD.ITMREF_0
left outer join
LIVE.ITMMASTER on STOLOT.ITMREF_0 = ITMMASTER.ITMREF_0
left outer join
LIVE.ZITMTSICOD6 on ITMMASTER.TSICOD_6 = ZITMTSICOD6.ID_0
left outer join
LIVE.ZITMTSICOD2 on ITMMASTER.TSICOD_2 = ZITMTSICOD2.ID_0
left outer join
(
SELECT
QLYCTLDEM_0,
QLYCRDASW.VCRLIN_0,
ITMREF_0,
MAX(CASE WHEN QLYCRDASW.QSTNUM_0 = 'UVALP110' THEN QLYCRDASW.ASW_0
ELSE NULL END) AS 'UV_Alpha',
MAX(CASE WHEN QLYCRDASW.QSTNUM_0 = 'UVBET110' THEN QLYCRDASW.ASW_0
ELSE NULL END) AS 'UV_Beta',
MAX(CASE WHEN QLYCRDASW.QSTNUM_0 = 'UVHSI110' THEN QLYCRDASW.ASW_0
ELSE NULL END) AS 'HSI',
MAX(CASE WHEN QLYCRDASW.QSTNUM_0 = 'OVMOI110' THEN QLYCRDASW.ASW_0
ELSE NULL END) AS 'Moisture',
MAX(CASE WHEN QLYCRDASW.QSTNUM_0 = 'DIOIL110' THEN QLYCRDASW.ASW_0
ELSE NULL END) AS 'Oil_by_Dist',
MAX(CASE WHEN QLYCRDASW.QSTNUM_0 = 'HPALP110' THEN QLYCRDASW.ASW_0
ELSE NULL END) AS 'HPLC Alpha',
MAX(CASE WHEN QLYCRDASW.QSTNUM_0 = 'HPBET110' THEN QLYCRDASW.ASW_0
ELSE NULL END) AS 'HPLC Beta',
MAX(CASE WHEN QLYCRDASW.QSTNUM_0 = 'HPCOH110' THEN QLYCRDASW.ASW_0
ELSE NULL END) AS 'HPLC Cohumulone',
MAX(CASE WHEN QLYCRDASW.QSTNUM_0 = 'HPCOL110' THEN QLYCRDASW.ASW_0
ELSE NULL END) AS 'HPLC Colupulone',
MAX(CASE WHEN QLYCRDASW.QSTNUM_0 = 'LCALP110' THEN QLYCRDASW.ASW_0
ELSE NULL END) AS 'Mebak Alpha 7.5',
MAX(CASE WHEN QLYCRDASW.QSTNUM_0 = 'LCALP310' THEN QLYCRDASW.ASW_0
ELSE NULL END) AS 'LCV Alpha 7.4',
MAX(CASE WHEN QLYCRDASW.QSTNUM_0 = 'GCBPI110' THEN QLYCRDASW.ASW_0
ELSE NULL END) AS 'Oil_B_Pinene',
MAX(CASE WHEN QLYCRDASW.QSTNUM_0 = 'GCMYR110' THEN QLYCRDASW.ASW_0
ELSE NULL END) AS 'Oil_Myrcene',
MAX(CASE WHEN QLYCRDASW.QSTNUM_0 = 'GCLIN110' THEN QLYCRDASW.ASW_0
ELSE NULL END) AS 'Oil_Linalool',
MAX(CASE WHEN QLYCRDASW.QSTNUM_0 = 'GCCAR110' THEN QLYCRDASW.ASW_0
ELSE NULL END) AS 'Oil_Caryophyllene',
MAX(CASE WHEN QLYCRDASW.QSTNUM_0 = 'GCFAR110' THEN QLYCRDASW.ASW_0
ELSE NULL END) AS 'Oil_Farnesene',
MAX(CASE WHEN QLYCRDASW.QSTNUM_0 = 'GCHUM110' THEN QLYCRDASW.ASW_0
ELSE NULL END) AS 'Oil_Humulene',
MAX(CASE WHEN QLYCRDASW.QSTNUM_0 = 'GCGEL110' THEN QLYCRDASW.ASW_0
ELSE NULL END) AS 'Oil_Geraniol'
FROM
LIVE.QLYCRDASW
GROUP BY QLYCTLDEM_0, QLYCRDASW.VCRLIN_0, ITMREF_0
) AS QLYCRDASW
ON (STOQLYD.VCRNUM_0 = QLYCRDASW.QLYCTLDEM_0) AND (STOQLYD.VCRLIN_0 =
QLYCRDASW.VCRLIN_0) AND (STOQLYD.ITMREF_0 = QLYCRDASW.ITMREF_0)
WHERE STOLOT.LOT_0 In(
SELECT Item
--FROM dbo.SplitString('17-OR277-001,PL1-YKUCTZ0012,DZJ25168',','))
FROM dbo.SplitString('PL1-YKUCTZ0012',','))
and (ISNUMERIC(UV_Alpha) = 1 or ISNUMERIC(UV_Beta) = 1 or
ISNUMERIC(HSI) = 1 or ISNUMERIC(Moisture) = 1 and ISNUMERIC(Oil_by_Dist) = 1
or ISNUMERIC([HPLC Alpha]) = 1
or ISNUMERIC([HPLC Beta]) = 1 or ISNUMERIC([HPLC Cohumulone]) = 1 or
ISNUMERIC([HPLC Colupulone]) = 1 or ISNUMERIC([Mebak Alpha 7.5]) = 1 or
ISNUMERIC([LCV Alpha 7.4]) = 1
or ISNUMERIC(Oil_B_Pinene) = 1 or ISNUMERIC(Oil_Myrcene) = 1 or
ISNUMERIC(Oil_Linalool) = 1 or ISNUMERIC(Oil_Caryophyllene) = 1 or
ISNUMERIC(Oil_Farnesene) = 1 or ISNUMERIC(Oil_Humulene) = 1
or ISNUMERIC(Oil_Geraniol) = 1)
thanks in advance
Have you tried using a form of RANK, probably DENSE_RANK? Here's a good site to explain them. You'd add that in the query and wrap the whole thing in another query, then add WHERE RankedColumn = 1. Make sense?
https://www.c-sharpcorner.com/article/rank-denserank-and-rownumber-functions-in-sql-server/
I know SQL Server Pivot, but this time I think I will need something more complex then a simple pivoted value.
Here it is an SQL fiddle example.
So I have a table where I have maximum 3 rows for one startcity - endcity combination.
In a query I need to get these combinations in just one row, and I need just those combinations, where there are 3 rows.
Please advice,
You can do this as a crosstab like this.
with NumberedValues as
(
SELECT EndCity
, StartDate
, EndDate
, Price
, ROW_NUMBER() OVER(PARTITION BY StartCity, EndCIty ORDER BY StartDate) as RowNum
FROM [dbo].[BestPrice]
)
SELECT EndCity,
max(CASE WHEN RowNum = 1 THEN StartDate END) as StartDate1,
max(CASE WHEN RowNum = 1 THEN Enddate END) as EndDate1,
max(CASE WHEN RowNum = 1 THEN Price END) as Price1,
max(CASE WHEN RowNum = 2 THEN StartDate END) as StartDate2,
max(CASE WHEN RowNum = 2 THEN Enddate END) as EndDate2,
max(CASE WHEN RowNum = 2 THEN Price END) as Price2,
max(CASE WHEN RowNum = 3 THEN StartDate END) as StartDate3,
max(CASE WHEN RowNum = 3 THEN Enddate END) as EndDate3,
max(CASE WHEN RowNum = 3 THEN Price END) as Price3
FROM NumberedValues
group by EndCity
I have a Query that selects Election data. Of course, when you start an election, there are 0 votes input for all candidates. But gradually, votes get entered. In order to get the percentage to output from the results, I took, number of votes multiplied by 100 then divided by total votes and I got my percentage.
Problem- once my query runs for the xml path, there is an error written in the top line of the xml document, "Divide by Zero error encountered". In order to bypass this, I just commented out the divide lines, but I would not like to do that. I figured, if I waited until there was a race that had votes in each field, I would then un-comment that line of code and let it output the percentage of only that race....until ALL races had at least some votes within them.
Here is my sql code:
:XML ON
select
max(case when seqnum = 1 then title1 end) as title1,
max(case when seqnum = 1 then [precinct percent] end) as PrecinctPercent,
max(case when seqnum = 1 then [candidate num] end) as WinnerNum,
max(case when seqnum = 1 then Votes end) as WinningVotes,
max(case when seqnum = 1 then party end) as WinningParty,
max(case when seqnum = 1 then leader end) as Winner,
max(case when seqnum = 1 then CAST(winner AS tinyint) end) as WinnerSelected,
max(case when seqnum = 1 then ((Votes * 100) / ([total vote])) end) as WinnerPercent,
max(case when seqnum = 2 then [candidate num] end) as LoserNum,
max(case when seqnum = 2 then Votes end) as LosingVotes,
max(case when seqnum = 2 then party end) as LosingParty,
max(case when seqnum = 2 then leader2 end) as Loser,
max(case when seqnum = 2 then ((Votes * 100) / ([total vote])) end) as LoserPercent,
max(case when seqnum = 2 then CAST(winner AS tinyint) end) as LoserSelected,
max(case when seqnum = 3 then title1 end) as title1,
max(case when seqnum = 3 then [precinct percent] end) as PrecinctPercent,
max(case when seqnum = 3 then [candidate num] end) as WinnerNum,
max(case when seqnum = 3 then Votes end) as WinningVotes,
max(case when seqnum = 3 then ((Votes * 100) / ([total vote])) end) as WinnerPercent,
max(case when seqnum = 3 then party end) as WinningParty,
max(case when seqnum = 3 then [first name]+ ' ' + [last name] end) as Winner,
max(case when seqnum = 3 then CAST(winner AS tinyint) end) as WinnerSelected,
max(case when seqnum = 4 then [precinct percent] end) as PrecinctPercent,
max(case when seqnum = 4 then [candidate num] end) as LoserNum,
max(case when seqnum = 4 then Votes end) as LosingVotes,
max(case when seqnum = 4 then ((Votes * 100) / ([total vote])) end) as LoserPercent,
max(case when seqnum = 4 then party end) as LosingParty,
max(case when seqnum = 4 then [first name]+ ' ' + [last name] end) as Loser,
max(case when seqnum = 4 then CAST(winner AS tinyint) end) as LoserSelected
from
(
select
r.title1,
r.[precinct percent],
r.[total vote],
rc.[race number],
rc.[candidate num],
rc.[Votes],
rc.[winner],
c.[party],
r.[leader],
r.[leader percent],
r.[leader2],
r.[leader2 percent],
c.[first name],
c.[last name],
row_number() over (partition by rc.[race number] order by votes desc) as seqnum
from dbo.[RACE CANDIDATES] rc
inner join dbo.[CANDIDATE] c on rc.[candidate num] = c.[candidate number]
inner join dbo.[RACE] r
on rc.[race number] = r.[race number]
) rc
group by rc.[race number]
FOR XML PATH ('ELECTION'), ROOT('root')
Is there a way I can have the select statement just "IGNORE" any fields that contain 0. Or choose to omit those that do contain 0 votes.
The total number of votes are being selected from the table "[RACE CANDIDATES]" if that helps. Hope it all makes sense.
Any input would be greatly appreciated.
Thanks All!
You can either put in a where in the sub select
WHERE r.[total vote] != 0
or you could use a case statment
CASE WHEN r.[total vote] = 0 THEN 0 ELSE Votes / r.[total vote] END