I am trying to add 2 values in a SQL Select Statement - sql

SELECT f.CaseId
, SUM(CASE WHEN f.FeeType = 29 THEN f.UnitCost END) AS AdminFee
, SUM(CASE WHEN f.FeeType = 1 THEN f.UnitCost END) AS SubFee
, SUM(CASE WHEN f.FeeType = 15 THEN f.UnitCost END) AS ContFee
FROM dbo.Fee f
GROUP BY f.CaseId
For the above query I am trying to add the UnitCost where FeeType=29 and FeeType=1 within the same select statement and Store it in TotalCost.

either you add a new line
sum (case when f.FeeType IN (1, 29) then f.UnitCost END) as TotalCost
or you use your query as a subquery and make an addition
select
CaseId,
AdminFee,
SubFee,
ContFee,
AdminFee + SubFee as TotalCost
from (
SELECT f.CaseId
, SUM(CASE WHEN f.FeeType = 29 THEN f.UnitCost END) AS AdminFee
, SUM(CASE WHEN f.FeeType = 1 THEN f.UnitCost END) AS SubFee
, SUM(CASE WHEN f.FeeType = 15 THEN f.UnitCost END) AS ContFee
FROM dbo.Fee f
GROUP BY f.CaseId) s

Related

SQL - % Breakout by Hour

I'm trying to write a query that will break out what percentage of time is utilized within a hour given a time range.
Sample data:
declare #date table(id int, Start_time time, End_time time)
Insert Into #date(id, Start_time, End_time) values
(0, '09:15', '17:15')
, (1, '10:45', '16:30')
, (2, '08:05', '17:45')
, (3, '07:00', '15:00')
, (4, '07:30', '8:30')
Looking to get output like this:
Any help would greatly be appreciated.
By using an ad-hoc tally table to create every minute of the day. This assumes you are processing to the minute. Then it becomes a small matter of the conditional aggregation.
Example
;with cte as (
Select A.ID
,Hrs = datepart(hour,T)
,Cnt = convert(decimal(10,2),sum(1.0) / 60)
From #date A
Join (
Select Top (1440) T=dateadd(MINUTE,-1+Row_Number() Over (Order By (Select NULL)),0) From master..spt_values n1,master..spt_values n2
) B on T >=convert(datetime,Start_Time) and t<convert(datetime,End_Time)
Group By A.ID,datepart(hour,T)
)
Select ID
,h3 = sum(case when Hrs=3 then Cnt else 0 end)
,h4 = sum(case when Hrs=4 then Cnt else 0 end)
,h5 = sum(case when Hrs=5 then Cnt else 0 end)
,h6 = sum(case when Hrs=6 then Cnt else 0 end)
,h7 = sum(case when Hrs=7 then Cnt else 0 end)
,h8 = sum(case when Hrs=8 then Cnt else 0 end)
,h9 = sum(case when Hrs=9 then Cnt else 0 end)
,h10 = sum(case when Hrs=10 then Cnt else 0 end)
,h11 = sum(case when Hrs=11 then Cnt else 0 end)
,h12 = sum(case when Hrs=12 then Cnt else 0 end)
,h13 = sum(case when Hrs=13 then Cnt else 0 end)
,h14 = sum(case when Hrs=14 then Cnt else 0 end)
,h15 = sum(case when Hrs=15 then Cnt else 0 end)
,h16 = sum(case when Hrs=16 then Cnt else 0 end)
,h17 = sum(case when Hrs=17 then Cnt else 0 end)
,h18 = sum(case when Hrs=18 then Cnt else 0 end)
From cte
Group By ID
Returns

How to Combine two pivot tables when both the tables are combined by inner Join function

Tag
SELECT TOP (1000) [System_Order_Id]
,[Batch_No]
,[Material_Code]
,[Set_Weight]
,[Actual_Weight]
FROM [master].[dbo].[Consumption_Report]
Batch No
System Id
Material Code
Set Weight
Actual Weight
1
1
1
Mat01
100
99
2
1
1
Mat02
50
55
3
1
1
Mat03
80
35
4
1
1
Mat04
40
20
SELECT TOP (1000)[Batch_End_TimeStamp]
,[Machine_Code]
, [User_Order_Id]
,[Batch_No]
,[Recipe_Code]
,[Cycle_Time]
,[System_Mode]
FROM [master].[dbo].[Batch_Report]
System Id
Batch No
Machine_Code
Recipe_Code
Cycle_Time
1
1
1
23
AA01
532
My Code:
WITH Consumption_Report AS (
SELECT
t1.Material_Code,
t1.Set_Weight,
t2.Batch_End_TimeStamp,
t2.Machine_Code,
t2.User_Order_Id,
t2.Recipe_Code,
t2.Cycle_Time
FROM
dbo.Consumption_Report t1
INNER JOIN dbo.Batch_Report t2 ON t2.Batch_No = t1.Batch_No
)
SELECT *
FROM Consumption_Report
PIVOT (AVG(Set_Weight) FOR Material_Code IN (Mat01,Mat02,Mat03,Mat04)) P
I want output like this:
Batch No
System Id
Machine_Code
Recipe_Code
Cycle_Time
Mat 01 Set Weight
Mat 01 Actual Weight
Mat 02 Set Weight
Mat 02 Actual Weight
Mat 03 Set Weight
Mat 03 Actual Weight
Mat 04 Set Weight
Mat 04 Actual Weight
1
1
1
23
AA01
532
100
99
50
55
80
35
40
20
I don't see what the second table has to do with anything. Just use conditional aggregation:
select Id, Batch_No, System_Id,
max(case when Material_Code = 'Mat01' then set_weight end) as mat01_set_weight,
max(case when Material_Code = 'Mat01' then actual_weight end) as mat01_actual_weight,
max(case when Material_Code = 'Mat02' then set_weight end) as mat02_set_weight,
max(case when Material_Code = 'Mat02' then actual_weight end) as mat02_actual_weight,
max(case when Material_Code = 'Mat03' then set_weight end) as mat03_set_weight,
max(case when Material_Code = 'Mat03' then actual_weight end) as mat03_actual_weight,
max(case when Material_Code = 'Mat04' then set_weight end) as mat04_set_weight,
max(case when Material_Code = 'Mat04' then actual_weight end) as mat04_actual_weight
from Consumption_Report
group by Id, Batch_No, System_Id;
SELECT * FROM Batch_Report
INNER JOIN (
select Batch_No,
sum(case when Material_Code = 'Mat01' then Set_Weight else 0 end) as Mat01,
sum(case when Material_Code = 'Mat01' then Actual_Weight else 0 end) as
Mat01_Act,
sum(case when Material_Code = 'Mat02' then Set_Weight else 0 end) as Mat02,
sum(case when Material_Code = 'Mat02' then Actual_Weight else 0 end) as
Mat02_Act,
sum(case when Material_Code = 'Mat03' then Set_Weight else 0 end) as Mat03,
sum(case when Material_Code = 'Mat03' then Actual_Weight else 0 end) as
Mat03_Act,
sum(case when Material_Code = 'Mat04' then Set_Weight else 0 end) as Mat04,
sum(case when Material_Code = 'Mat04' then Actual_Weight else 0 end) as Mat04_Act
from Consumption_Report
group by Batch_No) Consumption_Report
ON Batch_Report.Batch_No = Consumption_Report.Batch_No;

SQL equivalent when PIVOT is not available in SQL Server CE

I have a problem with a SQL query that runs correctly except on Microsoft SQL Server CE (no PIVOT support). The query is the following:
SELECT
*, [1] as IMGN1, [2] as IMGN2, [3] as IMGN3,
[4] as IMGN4, [5] as IMGN5, [6] as IMGN6,
[7] as IMGN7, [8] as IMGN8, [9] as IMGN9,
[10] as IMGN10
FROM
(SELECT
area.CoilId as CID, area.DEFECTID,
(SELECT SUM(s2.endposmd - s2.startposmd)
FROM sections s2
WHERE s2.OutCoilID = 999999
AND s2.InCoilId <= area.coilid) AS POSITIONMD,
d1.DNO as CAMERADEFECTNO, d1.IMAGE_NO as IMAGE_NO,
area.MERGEDTO as MERGEDTO
FROM
(OutCoils AS oc
INNER JOIN
sections AS s ON oc.OutCoilId = s.OutCoilId
INNER JOIN
defects AS area ON area.coilid = s.InCoilId
AND area.PositionMD >= s.StartPosMD
AND area.PositionMD <= s.EndPosMD
INNER JOIN
defects AS d1 ON d1.CoilId = area.CoilId
AND d1.MergedTo = area.DEFECTID)
WHERE
oc.OutCoilID = 999999 AND area.MergedTo = -2) AS SourceTable
PIVOT
(MIN([CAMERADEFECTNO]) FOR [IMAGE_NO]
IN ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10])
) AS PivotTable
ORDER BY
PositionMD;
How can this be translated to a valid SQL query for non PIVOT editions?
I tried something using CASE but I have a problem with the subquery inside the aggregate function I use to get POSITIONMD, the rest is already working properly. Any idea of how to get POSITIONMD?
SELECT
area.DEFECTID as DEFECTID,
min(CASE when d1.MERGEDTO = area.DEFECTID then area.COILID end) CID,
min(CASE when d1.MERGEDTO = area.DEFECTID then area.MERGEDTO end) MERGEDTO,
min(CASE when d1.MERGEDTO = area.DEFECTID then (select sum(s2.endposmd - s2.startposmd) from sections s2 where s2.OutCoilID=999999 and s2.InCoilId<=area.coilid) end) POSITIONMD,
sum(CASE when d1.IMAGE_NO = 1 then (d1.DNO) end) IMGN1,
sum(CASE when d1.IMAGE_NO = 2 then (d1.DNO) end) IMGN2,
sum(CASE when d1.IMAGE_NO = 3 then (d1.DNO) end) IMGN3,
sum(CASE when d1.IMAGE_NO = 4 then (d1.DNO) end) IMGN4,
sum(CASE when d1.IMAGE_NO = 5 then (d1.DNO) end) IMGN5,
sum(CASE when d1.IMAGE_NO = 6 then (d1.DNO) end) IMGN6,
sum(CASE when d1.IMAGE_NO = 7 then (d1.DNO) end) IMGN7,
sum(CASE when d1.IMAGE_NO = 8 then (d1.DNO) end) IMGN8,
sum(CASE when d1.IMAGE_NO = 9 then (d1.DNO) end) IMGN9,
sum(CASE when d1.IMAGE_NO = 10 then (d1.DNO) end) IMGN10
FROM ( steinb.OutCoils AS oc
INNER JOIN steinb.sections AS s ON oc.OutCoilId=s.OutCoilId
INNER JOIN steinb.defects AS area ON area.coilid=s.InCoilId AND area.PositionMD>=s.StartPosMD AND area.PositionMD<=s.EndPosMD
INNER JOIN steinb.defects AS d1 ON d1.CoilId=area.CoilId AND d1.MergedTo=area.DEFECTID AND d1.IMAGE_NO!=0)
WHERE oc.OutCoilID=999999 GROUP BY area.DEFECTID ORDER BY PositionMD;
Thank you a lot.
Gotcha. I believe you just need to remove the MIN:
SELECT
DEFECTID = area.DEFECTID
, CID = MIN(CASE when d1.MERGEDTO = area.DEFECTID then area.COILID end)
, MERGEDTO = MIN(CASE when d1.MERGEDTO = area.DEFECTID then area.MERGEDTO end)
, POSITIONMD = CASE when d1.MERGEDTO = area.DEFECTID then (select sum(s2.endposmd - s2.startposmd) from sections s2 where s2.OutCoilID=999999 and s2.InCoilId<=area.coilid) END
, IMGN1 = sum(CASE when d1.IMAGE_NO = 1 then (d1.DNO) END)
, IMGN2 = sum(CASE when d1.IMAGE_NO = 2 then (d1.DNO) end)
, IMGN3 = sum(CASE when d1.IMAGE_NO = 3 then (d1.DNO) end)
, IMGN4 = sum(CASE when d1.IMAGE_NO = 4 then (d1.DNO) end)
, IMGN5 = sum(CASE when d1.IMAGE_NO = 5 then (d1.DNO) end)
, IMGN6 = sum(CASE when d1.IMAGE_NO = 6 then (d1.DNO) end)
, IMGN7 = sum(CASE when d1.IMAGE_NO = 7 then (d1.DNO) end)
, IMGN8 = sum(CASE when d1.IMAGE_NO = 8 then (d1.DNO) end)
, IMGN9 = sum(CASE when d1.IMAGE_NO = 9 then (d1.DNO) end)
, IMGN10 = sum(CASE when d1.IMAGE_NO = 10 then (d1.DNO) end)
FROM ( steinb.OutCoils AS oc
INNER JOIN steinb.sections AS s ON oc.OutCoilId=s.OutCoilId
INNER JOIN steinb.defects AS area ON area.coilid=s.InCoilId AND area.PositionMD>=s.StartPosMD AND area.PositionMD<=s.EndPosMD
INNER JOIN steinb.defects AS d1 ON d1.CoilId=area.CoilId AND d1.MergedTo=area.DEFECTID AND d1.IMAGE_NO!=0)
WHERE oc.OutCoilID=999999 GROUP BY area.DEFECTID ORDER BY PositionMD;

SQL Select Adding a new row with difference between numbers

I have this query that give the sum between years but I want to add a new row at the end of each TARMA that give the differences between the years.
Here is the query:
Select
VPC.Armazem as TARMA
,YEAR(VPC.DATA) as DataTotal
,SUM(CASE WHEN VP.COMBUSTIVEL = 1 THEN VPL.QTD ELSE 0 END) as ADITIVADA
,SUM(CASE WHEN VP.COMBUSTIVEL = 2 THEN VPL.QTD ELSE 0 END) as X98
,SUM(CASE WHEN VP.COMBUSTIVEL = 3 THEN VPL.QTD ELSE 0 END)as X95
,SUM(CASE WHEN VP.COMBUSTIVEL = 4 THEN VPL.QTD ELSE 0 END) as XGAS
,SUM(CASE WHEN VP.COMBUSTIVEL = 5 THEN VPL.QTD ELSE 0 END) as XGPL
,SUM(CASE WHEN VP.COMBUSTIVEL = 6 THEN VPL.QTD ELSE 0 END) as XAGR
,SUM(CASE WHEN VP.COMBUSTIVEL = 7 THEN VPL.QTD ELSE 0 END) as MISTURA
,SUM(CASE WHEN VP.COMBUSTIVEL = 9 THEN VPL.QTD ELSE 0 END) as XAQ
,SUM(CASE WHEN VP.COMBUSTIVEL = 10 THEN VPL.QTD ELSE 0 END) as ADIESEL
,SUM(CASE WHEN VP.COMBUSTIVEL = 11 THEN VPL.QTD ELSE 0 END) as ADBLUE
,SUM(CASE WHEN VP.COMBUSTIVEL = 12 THEN VPL.QTD ELSE 0 END) as O95
,SUM(CASE WHEN VP.COMBUSTIVEL = 13 THEN VPL.QTD ELSE 0 END) as O98
WHERE
(MONTH(VPC.DATA) >= MONTH('2015-09-01') AND MONTH(VPC.DATA) <= MONTH('2015-09-30'))
and (YEAR(VPC.DATA) >= YEAR('2014-09-01') AND YEAR(VPC.DATA) <= YEAR('2015-09-30'))
and VPT.armazem IN ('454','457')
and FACT_VD NOT IN ('A', 'I', 'G', 'M')
GROUP BY
YEAR(VPC.DATA)
,VPC.Armazem
ORDER BY
VPC.Armazem
,YEAR(VPC.DATA)
And here is the result without the difference:
[Result][1]
For example:
TARMA: 454 for X98
2014: 1849.14077
2015: 2571.47750
Difference: -722,33673
I'm using MS SQL.
Is it with a UNION?
How can I get the difference?
If you want to calculate the difference in a separate query and then just "add" the rows to your results, you can use the "UNION ALL" between your queries. "UNION ALL" will just combine the 2 result sets. Using just "UNION" will cause SQL Server to attempt to de-duplicate the rows in the 2 result sets.
Using your query as a subquery (without the order by), you can do something like this:
with cte as (
<your query here>
)
select cte.*,
(additava - lag(additava) over (partition by Armazem order by DataTotal) ) as additava_diff,
. . .
from cte;
Note: lag() requires SQL Server 2012+.
EDIT:
Prior to SQL Server 2012+, you could do:
with cte as (
<your query here>
)
select cte.*,
(additava - cte2.additava) as additava_diff,
. . .
from cte outer apply
(select top 1 cte.*
from cte cte2
where cte2.Armazem = cte.Armazem and cte2.DataTotal < cte.DataTotal
order by cte2.DataTotal
) cte2
I got it:
;with dados as (
Select
VPC.Armazem as TARMA
,YEAR(VPC.DATA) as DataTotal1
,SUM(CASE WHEN VP.COMBUSTIVEL = 1 THEN VPL.QTD ELSE 0 END) as SomaADITIVADA
,SUM(CASE WHEN VP.COMBUSTIVEL = 2 THEN VPL.QTD ELSE 0 END) as SomaX98
,SUM(CASE WHEN VP.COMBUSTIVEL = 3 THEN VPL.QTD ELSE 0 END)as SomaX95
,SUM(CASE WHEN VP.COMBUSTIVEL = 4 THEN VPL.QTD ELSE 0 END) as SomaXGAS
,SUM(CASE WHEN VP.COMBUSTIVEL = 5 THEN VPL.QTD ELSE 0 END) as SomaXGPL
,SUM(CASE WHEN VP.COMBUSTIVEL = 6 THEN VPL.QTD ELSE 0 END) as SomaXAGR
,SUM(CASE WHEN VP.COMBUSTIVEL = 7 THEN VPL.QTD ELSE 0 END) as SomaMISTURA
,SUM(CASE WHEN VP.COMBUSTIVEL = 9 THEN VPL.QTD ELSE 0 END) as SomaXAQ
,SUM(CASE WHEN VP.COMBUSTIVEL = 10 THEN VPL.QTD ELSE 0 END) as SomaADIESEL
,SUM(CASE WHEN VP.COMBUSTIVEL = 11 THEN VPL.QTD ELSE 0 END) as SomaADBLUE
,SUM(CASE WHEN VP.COMBUSTIVEL = 12 THEN VPL.QTD ELSE 0 END) as SomaO95
,SUM(CASE WHEN VP.COMBUSTIVEL = 13 THEN VPL.QTD ELSE 0 END) as SomaO98
,row_number() over (partition by VPC.Armazem order by YEAR(VPC.DATA) ASC) as NAno
WHERE
(MONTH(VPC.DATA) >= MONTH('2015-09-01') AND MONTH(VPC.DATA) <= MONTH('2015-09-30'))
and (YEAR(VPC.DATA) >= YEAR('2014-09-01') AND YEAR(VPC.DATA) <= YEAR('2015-09-30'))
and VPT.armazem IN ('454','457')
and FACT_VD NOT IN ('A', 'I', 'G', 'M')
GROUP BY
YEAR(VPC.DATA)
,VPC.Armazem
)
SELECT
anosDetalhados.TARMA as TARMA
,anosDetalhados.DataTotal1 as DataTotal
,SUM(anosDetalhados.SomaADITIVADA) as ADITIVADA
,SUM(anosDetalhados.SomaX98) as X98
,SUM(anosDetalhados.SomaX95) as X95
,SUM(anosDetalhados.SomaXGAS) as XGAS
,SUM(anosDetalhados.SomaXGPL) as XGPL
,SUM(anosDetalhados.SomaXAGR) as XAGR
,SUM(anosDetalhados.SomaMISTURA) as MISTURA
,SUM(anosDetalhados.SomaXAQ) as XAQ
,SUM(anosDetalhados.SomaADIESEL) as ADIESEL
,SUM(anosDetalhados.SomaADBLUE) as ADBLUE
,SUM(anosDetalhados.SomaO95) as O95
,SUM(anosDetalhados.SomaO98) as O98
FROM dados as anosDetalhados (nolock)
GROUP BY
anosDetalhados.DataTotal1
,anosDetalhados.TARMA
UNION ALL
SELECT
ano1.TARMA as TARMA
,NULL as DataTotal
,SUM(coalesce(ano1.SomaADITIVADA-ano2.SomaADITIVADA, 0)) as ADITIVADA
,SUM(coalesce(ano1.SomaX98-ano2.SomaX98, 0)) as X98
,SUM(coalesce(ano1.SomaX95-ano2.SomaX95, 0)) as X95
,SUM(coalesce(ano1.SomaXGAS-ano2.SomaXGAS, 0)) as XGAS
,SUM(coalesce(ano1.SomaXGPL-ano2.SomaXGPL, 0)) as XGPL
,SUM(coalesce(ano1.SomaXAGR-ano2.SomaXAGR, 0)) as XAGR
,SUM(coalesce(ano1.SomaMISTURA-ano2.SomaMISTURA, 0)) as MISTURA
,SUM(coalesce(ano1.SomaXAQ-ano2.SomaXAQ, 0)) as XAQ
,SUM(coalesce(ano1.SomaADIESEL-ano2.SomaADIESEL, 0)) as ADIESEL
,SUM(coalesce(ano1.SomaADBLUE-ano2.SomaADBLUE, 0)) as ADBLUE
,SUM(coalesce(ano1.SomaO95-ano2.SomaO95, 0)) as O95
,SUM(coalesce(ano1.SomaO98-ano2.SomaO98, 0)) as O98
FROM dados as ano1 (nolock)
LEFT JOIN dados as ano2 on ano1.TARMA=ano2.TARMA and ano1.NAno > ano2.NAno
GROUP BY
ano1.TARMA
ORDER BY
TARMA
,anosDetalhados.DataTotal1 ASC

Sum data for many different results for same field

I am trying to find a better way to write this sql server code 2008. It works and data is accurate. Reason i ask is that i will be asked to do this for several other reports going forward and want to reduce the amount of code to upkeep going forward.
How can i take a field where i sum for the yes/no/- (dash) in each field without doing an individual sum as i have in code. Each table is a month of detail data which i sum using in a CTE. i changed the table name for each month and Union All to put data together. Is there a better way to do this. This is a small sample of code. Thanks for the help.
WITH H AS (
SELECT 'August' AS Month_Name
, SUM(CASE WHEN G.FFS = '-' THEN 1 ELSE 0 END) AS FFS_Dash
, SUM(CASE WHEN G.FFS = 'Yes' THEN 1 ELSE 0 END) AS FFS_Yes
, SUM(CASE WHEN G.FFS = 'No' THEN 1 ELSE 0 END) AS FFS_No
, SUM(CASE WHEN G.DNA = '-' THEN 1 ELSE 0 END) AS DNA_Dash
, SUM(CASE WHEN G.DNA = 'Yes' THEN 1 ELSE 0 END) AS DNA_Yes
, SUM(CASE WHEN G.DNA = 'No' THEN 1 ELSE 0 END) AS DNA_No
FROM table08 G )
, G AS (
SELECT 'July' AS Month_Name
, SUM(CASE WHEN G.FFS = '-' THEN 1 ELSE 0 END) AS FFS_Dash
, SUM(CASE WHEN G.FFS = 'Yes' THEN 1 ELSE 0 END) AS FFS_Yes
, SUM(CASE WHEN G.FFS = 'No' THEN 1 ELSE 0 END) AS FFS_No
, SUM(CASE WHEN G.DNA = '-' THEN 1 ELSE 0 END) AS DNA_Dash
, SUM(CASE WHEN G.DNA = 'Yes' THEN 1 ELSE 0 END) AS DNA_Yes
, SUM(CASE WHEN G.DNA = 'No' THEN 1 ELSE 0 END) AS DNA_No
FROM table07 G )
select * from H
UNION ALL
select * from G
How about:
SELECT Month_Name,
SUM(CASE WHEN G.FFS = '-' THEN 1 ELSE 0 END) AS FFS_Dash,
SUM(CASE WHEN G.FFS = 'Yes' THEN 1 ELSE 0 END) AS FFS_Yes,
SUM(CASE WHEN G.FFS = 'No' THEN 1 ELSE 0 END) AS FFS_No,
SUM(CASE WHEN G.DNA = '-' THEN 1 ELSE 0 END) AS DNA_Dash,
SUM(CASE WHEN G.DNA = 'Yes' THEN 1 ELSE 0 END) AS DNA_Yes,
SUM(CASE WHEN G.DNA = 'No' THEN 1 ELSE 0 END) AS DNA_No
FROM ((select 'July' as Month_Name, G.*
from table07 G
) union all
(select 'August', H.*
from table08 H
)
) gh
GROUP BY Month_Name;
However, having tables with the same structure is usually a sign of poor database design. You should have a single table with a column representing the month.