I need to show the sum of a column, like:
How can I create a sum of the "LQ's", for exemple:
0+0+38+1010+216+664
My code:
select pla.DSC_ACO,
sum(case when res.cod_ordem_producao like 'LQX%' then 1 else 0 end) as lqx,
sum(case when res.cod_ordem_producao like 'LQP%' then 1 else 0 end) as lqp,
sum(case when res.cod_ordem_producao like 'LQT%' then 1 else 0 end) as LQT,
sum(case when res.cod_ordem_producao like 'LQRT%' then 1 else 0 end) as lqrt,
sum(case when res.cod_ordem_producao like 'LQRZ%' then 1 else 0 end) as lqrz,
sum(case when res.cod_ordem_producao like 'LQZ%' then 1 else 0 end) as LQZ,
sum(case when res.cod_ordem_producao like 'LQRW%' then 1 else 0 end) as lqrw,
sum(case when res.cod_ordem_producao like 'LQW%' then 1 else 0 end) as LQW,
sum(case when res.cod_ordem_producao like 'LQ%' then 1 else 0 end) as Lq,
sum(case when res.cod_ordem_producao like 'LQR%' then 1 else 0 end) as LQR
from QT_QTS.RES_TUBO_REVENIMENTO2 res, QT_QTS.PLA_ORDEM_PRODUCAO pla
where res.COD_ORDEM_PRODUCAO = pla.COD_ORDEM_PRODUCAO
and res.DTH_CRIACAO_REG >= :dthini
and res.DTH_CRIACAO_REG <=:dthfim
group by pla.DSC_ACO
I hope it works :)
select pla.DSC_ACO,
sum(case when res.cod_ordem_producao like 'LQX%' then 1 else 0 end) as lqx,
sum(case when res.cod_ordem_producao like 'LQP%' then 1 else 0 end) as lqp,
sum(case when res.cod_ordem_producao like 'LQT%' then 1 else 0 end) as LQT,
sum(case when res.cod_ordem_producao like 'LQRT%' then 1 else 0 end) as lqrt,
sum(case when res.cod_ordem_producao like 'LQRZ%' then 1 else 0 end) as lqrz,
sum(case when res.cod_ordem_producao like 'LQZ%' then 1 else 0 end) as LQZ,
sum(case when res.cod_ordem_producao like 'LQRW%' then 1 else 0 end) as lqrw,
sum(case when res.cod_ordem_producao like 'LQW%' then 1 else 0 end) as LQW,
sum(case when res.cod_ordem_producao like 'LQ%' then 1 else 0 end) as Lq,
sum(case when res.cod_ordem_producao like 'LQR%' then 1 else 0 end) as LQR
from QT_QTS.RES_TUBO_REVENIMENTO2 res, QT_QTS.PLA_ORDEM_PRODUCAO pla
where res.COD_ORDEM_PRODUCAO = pla.COD_ORDEM_PRODUCAO
and res.DTH_CRIACAO_REG >= :dthini
and res.DTH_CRIACAO_REG <=:dthfim
group by pla.DSC_ACO
UNION ALL
SELECT
'TOTAL' DSC,
SUM(lqx),
SUM(lqp),
SUM(LQT),
SUM(lqrt),
SUM(qrz),
SUM(LQZ),
SUM(lqrw),
SUM(LQW),
SUM(Lq),
SUM(LQR)
FROM (select pla.DSC_ACO,
sum(case when res.cod_ordem_producao like 'LQX%' then 1 else 0 end) as lqx,
sum(case when res.cod_ordem_producao like 'LQP%' then 1 else 0 end) as lqp,
sum(case when res.cod_ordem_producao like 'LQT%' then 1 else 0 end) as LQT,
sum(case when res.cod_ordem_producao like 'LQRT%' then 1 else 0 end) as lqrt,
sum(case when res.cod_ordem_producao like 'LQRZ%' then 1 else 0 end) as lqrz,
sum(case when res.cod_ordem_producao like 'LQZ%' then 1 else 0 end) as LQZ,
sum(case when res.cod_ordem_producao like 'LQRW%' then 1 else 0 end) as lqrw,
sum(case when res.cod_ordem_producao like 'LQW%' then 1 else 0 end) as LQW,
sum(case when res.cod_ordem_producao like 'LQ%' then 1 else 0 end) as Lq,
sum(case when res.cod_ordem_producao like 'LQR%' then 1 else 0 end) as LQR
from QT_QTS.RES_TUBO_REVENIMENTO2 res, QT_QTS.PLA_ORDEM_PRODUCAO pla
where res.COD_ORDEM_PRODUCAO = pla.COD_ORDEM_PRODUCAO
and res.DTH_CRIACAO_REG >= :dthini
and res.DTH_CRIACAO_REG <=:dthfim
group by pla.DSC_ACO)
You may use a simple query like this to obtain the result for LQR% predicate that you request in your question
select count(*) as LQR
from QT_QTS.RES_TUBO_REVENIMENTO2 res
join QT_QTS.PLA_ORDEM_PRODUCAO pla on res.COD_ORDEM_PRODUCAO = pla.COD_ORDEM_PRODUCAO
where res.DTH_CRIACAO_REG >= :dthini
and res.DTH_CRIACAO_REG <=:dthfim
and res.cod_ordem_producao like 'LQR%'
select sum(lqx), sum(lqp), sum(lqt), sum(lqrt), sum(lqrz), sum(lqz), sum(lqrw),
sum(lqw), sum(lq)
, sum(lqr) from
(select pla.DSC_ACO,
sum(case when res.cod_ordem_producao like 'LQX%' then 1 else 0 end) as lqx,
sum(case when res.cod_ordem_producao like 'LQP%' then 1 else 0 end) as lqp,
sum(case when res.cod_ordem_producao like 'LQT%' then 1 else 0 end) as LQT,
sum(case when res.cod_ordem_producao like 'LQRT%' then 1 else 0 end) as lqrt,
sum(case when res.cod_ordem_producao like 'LQRZ%' then 1 else 0 end) as lqrz,
sum(case when res.cod_ordem_producao like 'LQZ%' then 1 else 0 end) as LQZ,
sum(case when res.cod_ordem_producao like 'LQRW%' then 1 else 0 end) as lqrw,
sum(case when res.cod_ordem_producao like 'LQW%' then 1 else 0 end) as LQW,
sum(case when res.cod_ordem_producao like 'LQ%' then 1 else 0 end) as Lq,
sum(case when res.cod_ordem_producao like 'LQR%' then 1 else 0 end) as LQR
from QT_QTS.RES_TUBO_REVENIMENTO2 res, QT_QTS.PLA_ORDEM_PRODUCAO pla
where res.COD_ORDEM_PRODUCAO = pla.COD_ORDEM_PRODUCAO
and res.DTH_CRIACAO_REG >= :dthini
and res.DTH_CRIACAO_REG <=:dthfim
group by pla.DSC_ACO) as values
Use a Common Table Expression to organize the data you want, then just select from it with a simple summation. The CTE in the WITH clause will allow you to select from that just like it were a normal table.
WITH temp_table AS (
select pla.DSC_ACO,
case when res.cod_ordem_producao like 'LQX%' then 1 else 0 end as LQX,
case when res.cod_ordem_producao like 'LQP%' then 1 else 0 end as LQP,
case when res.cod_ordem_producao like 'LQT%' then 1 else 0 end as LQT,
case when res.cod_ordem_producao like 'LQRT%' then 1 else 0 end as LQRT,
case when res.cod_ordem_producao like 'LQRZ%' then 1 else 0 end as LQRZ,
case when res.cod_ordem_producao like 'LQZ%' then 1 else 0 end as LQZ,
case when res.cod_ordem_producao like 'LQRW%' then 1 else 0 end as LQRW,
case when res.cod_ordem_producao like 'LQW%' then 1 else 0 end as LQW,
case when res.cod_ordem_producao like 'LQR%' then 1 else 0 end as LQR,
case when res.cod_ordem_producao like 'LQ%' then 1 else 0 end as LQ
from QT_QTS.RES_TUBO_REVENIMENTO2 res, QT_QTS.PLA_ORDEM_PRODUCAO pla
where res.COD_ORDEM_PRODUCAO = pla.COD_ORDEM_PRODUCAO
and res.DTH_CRIACAO_REG >= :dthini
and res.DTH_CRIACAO_REG <= :dthfim)
SELECT SUM(LQ) AS LQ_SUM FROM temp_table
You didn't specify the final format you needed the query in, but your question only asked how do you get the sum of that column. If you need to expand the logic to include other aggregations, you should be able to see how to add more fields to the final SELECT statement there.
Also, you should note that you are going to be double counting some data. For example, LQR will also be counting the same values as in LQRT, LQRZ, and LQRW. And, the LQ will count the same things as all of the fields. This might be the behavior you want, but if you want a unique bin for each value to fall in, you are going to need to do some more logic manipulation to it first.
Related
I need to use the "DirectQuery" function on PowerBI Desktop.
When i try to load the data PBI stops the process because of the "SET DATEFIRST 1" instruction at the beginning of the query.
That happens because PBI elaborates the request like 'SELECT * FROM (Myquery)' and that throws a syntax error near "SET".
I'm asking you if there is a way that allows me to set Monday as the first day of the week without using the "SET DATEFIRST 1" instruction.
Here it is the query i'm talking about:
SET DATEFIRST 1;
SELECT SUM(Tabella2.DC20) AS DC20,
SUM(Tabella2.OT20) AS OT20,
SUM(Tabella2.FR20) AS FR20,
SUM(Tabella2.RF20) AS RF20,
SUM(Tabella2.DC40) AS DC40,
SUM(Tabella2.OT40) AS OT40,
SUM(Tabella2.FR40) AS FR40,
SUM(Tabella2.RH40) AS RH40,
SUM(Tabella2.HC40) AS HC40,
SUM(Tabella2.HP40) AS HW40,
SUM(Tabella2.HC45) AS HC45,
SUM(Tabella2.HP45) AS HP45,
SUM(Tabella2.Altri) AS Altri,
Tabella2.YEAR,
Tabella2.month
FROM (SELECT SUM(CASE GET.Abbreviation WHEN '20DV' THEN 1 ELSE 0 END) AS DC20,
SUM(CASE GET.Abbreviation WHEN '20OT' THEN 1 ELSE 0 END) AS OT20,
SUM(CASE GET.Abbreviation WHEN '20FL' THEN 1 ELSE 0 END) AS FR20,
SUM(CASE GET.Abbreviation WHEN '20RE' THEN 1 ELSE 0 END) AS RF20,
SUM(CASE GET.Abbreviation WHEN '40DV' THEN 1 ELSE 0 END) AS DC40,
SUM(CASE GET.Abbreviation WHEN '40OT' THEN 1 ELSE 0 END) AS OT40,
SUM(CASE GET.Abbreviation WHEN '40FL' THEN 1 ELSE 0 END) AS FR40,
SUM(CASE GET.Abbreviation WHEN '40HR' THEN 1 ELSE 0 END) AS RH40,
SUM(CASE GET.Abbreviation WHEN '40HC' THEN 1 ELSE 0 END) AS HC40,
SUM(CASE GET.Abbreviation WHEN '40HP' THEN 1 ELSE 0 END) AS HP40,
SUM(CASE GET.Abbreviation WHEN '45HC' THEN 1 ELSE 0 END) AS HC45,
SUM(CASE GET.Abbreviation WHEN '45HP' THEN 1 ELSE 0 END) AS HP45,
SUM(CASE
WHEN GET.Abbreviation != '20DV'
AND GET.Abbreviation != '20OT'
AND GET.Abbreviation != '20FL'
AND GET.Abbreviation != '20RE'
AND GET.Abbreviation != '40DV'
AND GET.Abbreviation != '40OT'
AND GET.Abbreviation != '40FL'
AND GET.Abbreviation != '40HR'
AND GET.Abbreviation != '40HC'
AND GET.Abbreviation != '40HP'
AND GET.Abbreviation != '45HC'
AND GET.Abbreviation != '45HP' THEN 1
ELSE 0
END) AS Altri,
GV.Vessel_Name,
GVPC.Import_Documentation_Voyage_Number,
GVPC.Actual_Arrival_Time,
DATEPART(MONTH, GVPC.Actual_Arrival_Time) AS month,
DATEPART(YEAR, GVPC.Actual_Arrival_Time) AS YEAR
FROM [My_DB].[dbo].[GISEquipment] GE,
[Interlink_Main90].[dbo].[GISEquipment_Type] GET,
[Interlink_Main90].[dbo].[Equipment_Cycle] EC,
[Interlink_Main90].[dbo].[Equipment_Cycle_Type] ECT,
[Interlink_Main90].[dbo].[Equipment_Event] EE,
[Interlink_Main90].[dbo].[Equipment_Event_Type] EET,
[Interlink_Main90].[dbo].[GISLocation] GL,
[Interlink_Main90].[dbo].[GISPort] GP,
[Interlink_Main90].[dbo].[GISVoyage] GV,
[Interlink_Main90].[dbo].GISVoyage_Port_Call GVPC,
[Interlink_Main90].[dbo].GISVessel GVE
WHERE GE.Equipment_Type_id = GET.Equipment_Type_id
AND GE.Equipment_id = EC.Equipment_id
AND EC.Eq_Cycle_Type_id = ECT.Eq_Cycle_Type_id
AND EC.Eq_Cycle_id = EE.EQ_Cycle_id
AND EE.EQEV_Type_id = EET.EqEv_Type_id
AND EE.Location_id = GL.Location_id
AND EC.POD_id = GP.Port_id
AND EET.Name IN ('IDV')
AND GL.Global_Name = 'Leghorn'
AND GP.Global_Name = 'Leghorn'
AND EE.[Logical_Cancel] = '0'
AND GVPC.Voyage_Port_Call_id = EC.Voyage_Port_Call_id
AND GV.Vessel_id = GVE.Vessel_id
AND GVPC.Voyage_id = GV.Voyage_id
AND GVPC.Port_id = GP.Port_id
AND GV.Logical_Cancel_Value = 0
AND GVPC.Logical_Cancel_Value = 0
AND GVE.Logical_Cancel_Value = 0
AND GVPC.Import_Documentation_Voyage_Number IS NOT NULL
AND GVPC.Actual_Arrival_Time IS NOT NULL
GROUP BY GV.Vessel_Name,
GVPC.Import_Documentation_Voyage_Number,
GVPC.Actual_Arrival_Time) Tabella2
WHERE YEAR = '2022'
GROUP BY Tabella2.YEAR,
Tabella2.month
ORDER BY YEAR DESC,
month;
SET DATEFIRST 7;
Thanks in advance for the help.
I am trying to join these two tables, or use a sub-query to achieve the results I need.
As of now I have the first query pulling hourly totals with a overall total between MIN(time) and MAX(time). I need to join the second query to get the total scans from MIN(time) and MAX(time)
Any ideas of where I could be going wrong?
select
UPPER(t.operator) as Operator,
CASE WHEN t.eventtype = 'Replenishment Complete' THEN (SUM(CASE WHEN DATEPART(HOUR,t.time) = 6 THEN 1 ELSE 0 END)) ELSE NULL END AS '6AM',
CASE WHEN t.eventtype = 'Replenishment Complete' THEN (SUM(CASE WHEN DATEPART(HOUR,t.time) = 7 THEN 1 ELSE 0 END)) ELSE NULL END AS '7AM',
CASE WHEN t.eventtype = 'Replenishment Complete' THEN (SUM(CASE WHEN DATEPART(HOUR,t.time) = 8 THEN 1 ELSE 0 END)) ELSE NULL END AS '8AM',
CASE WHEN t.eventtype = 'Replenishment Complete' THEN (SUM(CASE WHEN DATEPART(HOUR,t.time) = 9 THEN 1 ELSE 0 END)) ELSE NULL END AS '9AM',
CASE WHEN t.eventtype = 'Replenishment Complete' THEN (SUM(CASE WHEN DATEPART(HOUR,t.time) = 10 THEN 1 ELSE 0 END)) ELSE NULL END AS '10AM',
CASE WHEN t.eventtype = 'Replenishment Complete' THEN (SUM(CASE WHEN DATEPART(HOUR,t.time) = 11 THEN 1 ELSE 0 END)) ELSE NULL END AS '11AM',
CASE WHEN t.eventtype = 'Replenishment Complete' THEN (SUM(CASE WHEN DATEPART(HOUR,t.time) = 12 THEN 1 ELSE 0 END)) ELSE NULL END AS '12PM',
CASE WHEN t.eventtype = 'Replenishment Complete' THEN (SUM(CASE WHEN DATEPART(HOUR,t.time) = 13 THEN 1 ELSE 0 END)) ELSE NULL END AS '1PM',
CASE WHEN t.eventtype = 'Replenishment Complete' THEN (SUM(CASE WHEN DATEPART(HOUR,t.time) = 14 THEN 1 ELSE 0 END)) ELSE NULL END AS '2PM',
CASE WHEN t.eventtype = 'Replenishment Complete' THEN (SUM(CASE WHEN DATEPART(HOUR,t.time) = 15 THEN 1 ELSE 0 END)) ELSE NULL END AS '3PM',
CASE WHEN t.eventtype = 'Replenishment Complete' THEN (SUM(CASE WHEN DATEPART(HOUR,t.time) = 16 THEN 1 ELSE 0 END)) ELSE NULL END AS '4PM',
CASE WHEN t.eventtype = 'Replenishment Complete' THEN (SUM(CASE WHEN DATEPART(HOUR,t.time) = 17 THEN 1 ELSE 0 END)) ELSE NULL END AS '5PM',
CASE WHEN t.eventtype = 'Replenishment Complete' THEN (COUNT(CASE WHEN DATEPART(HOUR,t.time) > 17 THEN t.eventtype ELSE NULL END)) ELSE NULL END AS '6+PM',
SUM(CASE WHEN t.eventtype = 'Replenishment Complete' THEN 1 ELSE 0 END) as TotalCanisters
from mck_hvs.replevent t
where
CAST(t.time as DATE) = CAST(GETDATE() as DATE)
and t.stationtype IN ('T', 'S')
and t.eventtype = 'Replenishment Complete'
group by
t.operator,
t.eventtype
Second query:
select
UPPER(o.operator) as Operator,
SUM(CASE WHEN o.eventtype = 'GoodScan' THEN 1 ELSE 0 END) as TotalScans,
convert( varchar(19), MIN(o.time), 8) as LogonTime,
DATEDIFF(MINUTE, MIN(o.time), MAX(o.time)) as TotalMinLogon
from mck_hvs.replevent o
where
CAST(o.time as DATE) = CAST(GETDATE() as DATE)
and o.eventtype IN ( 'Replenishment Complete', 'GoodScan' )
group by
o.operator
order by o.operator
Something like the below should get you headed to a solution. I removed the group on t.eventtype and removed from the case statements because the where clause already limited the results for you.
select
op.Operator,
op.TotalScans,
op.LogonTime,
op.TotalMinLogon,
b.[6AM],
b.[7AM],
b.[8AM],
b.[9AM],
b.[10AM],
b.[11AM],
b.[12PM],
b.[1PM],
b.[2PM],
b.[3PM],
b.[4PM],
b.[5PM],
b.[6+PM]
from
(
select
UPPER(o.operator) as Operator,
SUM(CASE WHEN o.eventtype = 'GoodScan' THEN 1 ELSE 0 END) as TotalScans,
convert( varchar(19), MIN(o.time), 8) as LogonTime,
DATEDIFF(MINUTE, MIN(o.time), MAX(o.time)) as TotalMinLogon
from mck_hvs.replevent o
where
--will use o.time index now:
o.time >= CAST(GETDATE() as DATE)
and o.time < CAST(dateadd(Day,1,GETDATE()) as DATE)
and o.eventtype IN ( 'Replenishment Complete', 'GoodScan' )
group by
o.operator
) as op
left join
(
select
UPPER(t.operator) as Operator,
SUM(CASE WHEN DATEPART(HOUR,t.time) = 6 THEN 1 ELSE 0 END) AS '6AM',
SUM(CASE WHEN DATEPART(HOUR,t.time) = 7 THEN 1 ELSE 0 END) AS '7AM',
SUM(CASE WHEN DATEPART(HOUR,t.time) = 8 THEN 1 ELSE 0 END) AS '8AM',
SUM(CASE WHEN DATEPART(HOUR,t.time) = 9 THEN 1 ELSE 0 END) AS '9AM',
SUM(CASE WHEN DATEPART(HOUR,t.time) = 10 THEN 1 ELSE 0 END) AS '10AM',
SUM(CASE WHEN DATEPART(HOUR,t.time) = 11 THEN 1 ELSE 0 END) AS '11AM',
SUM(CASE WHEN DATEPART(HOUR,t.time) = 12 THEN 1 ELSE 0 END) AS '12PM',
SUM(CASE WHEN DATEPART(HOUR,t.time) = 13 THEN 1 ELSE 0 END) AS '1PM',
SUM(CASE WHEN DATEPART(HOUR,t.time) = 14 THEN 1 ELSE 0 END) AS '2PM',
SUM(CASE WHEN DATEPART(HOUR,t.time) = 15 THEN 1 ELSE 0 END) AS '3PM',
SUM(CASE WHEN DATEPART(HOUR,t.time) = 16 THEN 1 ELSE 0 END) AS '4PM',
SUM(CASE WHEN DATEPART(HOUR,t.time) = 17 THEN 1 ELSE 0 END) AS '5PM',
SUM(CASE WHEN DATEPART(HOUR,t.time) > 17 THEN 1 ELSE 0 END) AS '6+PM',
SUM(CASE WHEN t.eventtype = 'Replenishment Complete' THEN 1 ELSE 0 END) as TotalCanisters
from mck_hvs.replevent t
where
--will use o.time index now:
o.time >= CAST(GETDATE() as DATE)
and o.time < CAST(dateadd(Day,1,GETDATE()) as DATE)
and t.stationtype IN ('T', 'S')
and t.eventtype = 'Replenishment Complete'
group by
t.operator
) as b
on b.Operator = op.Operator
SELECT l.* ,
r.TotalScans ,
r.LogonTime ,
r.TotalMinLogon
FROM ( SELECT UPPER(t.operator) AS Operator ,
CASE WHEN t.eventtype = 'Replenishment Complete'
THEN ( SUM(CASE WHEN DATEPART(HOUR, t.time) = 6
THEN 1
ELSE 0
END) )
ELSE NULL
END AS '6AM' ,
CASE WHEN t.eventtype = 'Replenishment Complete'
THEN ( SUM(CASE WHEN DATEPART(HOUR, t.time) = 7
THEN 1
ELSE 0
END) )
ELSE NULL
END AS '7AM' ,
CASE WHEN t.eventtype = 'Replenishment Complete'
THEN ( SUM(CASE WHEN DATEPART(HOUR, t.time) = 8
THEN 1
ELSE 0
END) )
ELSE NULL
END AS '8AM' ,
CASE WHEN t.eventtype = 'Replenishment Complete'
THEN ( SUM(CASE WHEN DATEPART(HOUR, t.time) = 9
THEN 1
ELSE 0
END) )
ELSE NULL
END AS '9AM' ,
CASE WHEN t.eventtype = 'Replenishment Complete'
THEN ( SUM(CASE WHEN DATEPART(HOUR, t.time) = 10
THEN 1
ELSE 0
END) )
ELSE NULL
END AS '10AM' ,
CASE WHEN t.eventtype = 'Replenishment Complete'
THEN ( SUM(CASE WHEN DATEPART(HOUR, t.time) = 11
THEN 1
ELSE 0
END) )
ELSE NULL
END AS '11AM' ,
CASE WHEN t.eventtype = 'Replenishment Complete'
THEN ( SUM(CASE WHEN DATEPART(HOUR, t.time) = 12
THEN 1
ELSE 0
END) )
ELSE NULL
END AS '12PM' ,
CASE WHEN t.eventtype = 'Replenishment Complete'
THEN ( SUM(CASE WHEN DATEPART(HOUR, t.time) = 13
THEN 1
ELSE 0
END) )
ELSE NULL
END AS '1PM' ,
CASE WHEN t.eventtype = 'Replenishment Complete'
THEN ( SUM(CASE WHEN DATEPART(HOUR, t.time) = 14
THEN 1
ELSE 0
END) )
ELSE NULL
END AS '2PM' ,
CASE WHEN t.eventtype = 'Replenishment Complete'
THEN ( SUM(CASE WHEN DATEPART(HOUR, t.time) = 15
THEN 1
ELSE 0
END) )
ELSE NULL
END AS '3PM' ,
CASE WHEN t.eventtype = 'Replenishment Complete'
THEN ( SUM(CASE WHEN DATEPART(HOUR, t.time) = 16
THEN 1
ELSE 0
END) )
ELSE NULL
END AS '4PM' ,
CASE WHEN t.eventtype = 'Replenishment Complete'
THEN ( SUM(CASE WHEN DATEPART(HOUR, t.time) = 17
THEN 1
ELSE 0
END) )
ELSE NULL
END AS '5PM' ,
CASE WHEN t.eventtype = 'Replenishment Complete'
THEN ( COUNT(CASE WHEN DATEPART(HOUR, t.time) > 17
THEN t.eventtype
ELSE NULL
END) )
ELSE NULL
END AS '6+PM' ,
SUM(CASE WHEN t.eventtype = 'Replenishment Complete'
THEN 1
ELSE 0
END) AS TotalCanisters
FROM #replevent t
WHERE CAST(t.time AS DATE) = CAST(GETDATE() AS DATE)
AND t.stationtype IN ( 'T', 'S' )
AND t.eventtype = 'Replenishment Complete'
GROUP BY t.operator ,
t.eventtype
) AS l
INNER JOIN ( SELECT UPPER(o.operator) AS Operator_r ,
SUM(CASE WHEN o.eventtype = 'GoodScan' THEN 1
ELSE 0
END) AS TotalScans ,
CONVERT(VARCHAR(19), MIN(o.time), 8) AS LogonTime ,
DATEDIFF(SECOND, MIN(o.time), MAX(o.time)) AS TotalMinLogon
FROM #replevent o
WHERE CAST(o.time AS DATE) = CAST(GETDATE() AS DATE)
AND o.eventtype IN ( 'Replenishment Complete',
'GoodScan' )
GROUP BY o.operator
) AS r ON l.Operator = r.Operator_r
ORDER BY l.Operator;
I have the following 2 queries:
Query 1:
WITH JobTransactionsSumTypes AS
(
SELECT
[Job],
[Cost_Code],
SUM(CASE WHEN [Transaction_Type] = 'AP cost' AND [Commitment] <>'' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS APcostAmountComSum,
SUM(CASE WHEN [Transaction_Type] = 'AP cost' AND [Commitment] ='' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS APcostAmountNonComSum,
SUM(CASE WHEN [Transaction_Type] = 'Approved est changes' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS ApprovedEstChangesAmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Aprvd cmmtt cst chng' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS AprvdCmmttCstChngAmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Aprvd schdl val chn' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS AprvdSchdlValChnAmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Cash receipt' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS CashReceiptAmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Committed cost' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS CommittedCostAmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Dollars paid' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS DollarsPaidAmountSum,
SUM(CASE WHEN [Transaction_Type] = 'General Ledger only' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS GeneralLedgerOnlyAmountSum,
SUM(CASE WHEN [Transaction_Type] = 'JC cost' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS JCcostAmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Misc worksheet 1' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS MiscWorksheet1AmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Misc worksheet 2' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS MiscWorksheet2AmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Misc worksheet 3' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS MiscWorksheet3AmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Misc worksheet 4' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS MiscWorksheet4AmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Original estimate' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS OriginalEstimateAmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Pending est changes' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS PendingEstChangesAmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Percent complete' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS PercentCompleteAmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Pndng cmmtt cst chng' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS PndngCmmttCstChngAmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Pndng schd val chg 2' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS PndngSchdValChg2AmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Pndng schd val chg 3' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS PndngSchdValChg3AmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Pndng schdl val chng' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS PndngSchdlValChngAmountSum,
SUM(CASE WHEN [Transaction_Type] = 'PR cost' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS PRcostAmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Receivable Adjstment' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS ReceivableAdjstmentAmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Retention billed' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS RetentionBilledAmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Scheduled value' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS ScheduledValueAmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Work Billed' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS WorkBilledAmountSum
FROM [ADCData_Doric].[dbo].[JCT_CURRENT__TRANSACTION]
WHERE
GROUP BY
[Job],
[Cost_Code]
)
SELECT
Job,
Cost_Code,
APcostAmountComSum,
APcostAmountNonComSum,
ApprovedEstChangesAmountSum,
AprvdCmmttCstChngAmountSum,
AprvdSchdlValChnAmountSum,
CashReceiptAmountSum,
CommittedCostAmountSum,
DollarsPaidAmountSum,
GeneralLedgerOnlyAmountSum,
JCcostAmountSum,
MiscWorksheet1AmountSum,
MiscWorksheet2AmountSum,
MiscWorksheet3AmountSum,
MiscWorksheet4AmountSum,
OriginalEstimateAmountSum,
PendingEstChangesAmountSum,
PercentCompleteAmountSum,
PndngCmmttCstChngAmountSum,
PndngSchdValChg2AmountSum,
PndngSchdValChg3AmountSum,
PndngSchdlValChngAmountSum,
PRcostAmountSum,
ReceivableAdjstmentAmountSum,
RetentionBilledAmountSum,
ScheduledValueAmountSum,
WorkBilledAmountSum,
(ScheduledValueAmountSum) AS StartContractAmount,
(AprvdSchdlValChnAmountSum) AS ApprovedVariations,
(OriginalEstimateAmountSum + ApprovedEstChangesAmountSum + PendingEstChangesAmountSum) AS TotalBudgetOriginalApprovedPending,
(OriginalEstimateAmountSum + ApprovedEstChangesAmountSum)*(MiscWorksheet1AmountSum/100)+(PendingEstChangesAmountSum*(MiscWorksheet2AmountSum/100)) AS TotalCommitmentsBudget,
(CommittedCostAmountSum + AprvdCmmttCstChngAmountSum + PndngCmmttCstChngAmountSum) AS ApprovedPendingCommitedCosts
-- You Could Add additional Calculations here.
FROM
[JobTransactionsSumTypes]
Query 2:
SELECT
APM_MASTER__DISTRIBUTION.Job
, APM_MASTER__DISTRIBUTION.Cost_Code
,SUM(CASE WHEN APM_MASTER__DISTRIBUTION.Onhold_Status <>0 THEN JCT_CURRENT__TRANSACTION.Amount-JCT_CURRENT__TRANSACTION.Noncosted_Tax ELSE 0 END) AS OnHoldAmount
,SUM(CASE WHEN APM_MASTER__DISTRIBUTION.Onhold_Status =0 THEN JCT_CURRENT__TRANSACTION.Amount-JCT_CURRENT__TRANSACTION.Noncosted_Tax ELSE 0 END) AS NotOnHoldAmount
FROM
dbo.JCT_CURRENT__TRANSACTION JCT_CURRENT__TRANSACTION
LEFT OUTER JOIN dbo.APM_MASTER__DISTRIBUTION APM_MASTER__DISTRIBUTION
ON JCT_CURRENT__TRANSACTION.Vendor = APM_MASTER__DISTRIBUTION.Vendor AND JCT_CURRENT__TRANSACTION.Invoice = APM_MASTER__DISTRIBUTION.Invoice AND JCT_CURRENT__TRANSACTION.Dist_Sequence = APM_MASTER__DISTRIBUTION.Dist_Seq
GROUP BY
APM_MASTER__DISTRIBUTION.Job
, APM_MASTER__DISTRIBUTION.Cost_Code
I can join these in Crystal reports, but would like to move this into a single query through left outer joining (getting all Query 1 Results) and linking through the job and cost code to query 2.
I suppose what I am asking is, Query 1 uses a common table expression but query 2 does not, and i'm not sure how to join them.
Thanks.
You can use multiple CTE in one query
Simple example:
;WITH cte1 AS
(
SELECT *
FROM table1
), AS cte2
(
SELECT *
FROM table2
)
SELECT *
FROM cte1 c1 LEFT JOIN cte2 c2 ON c1.id = c2.id
Your query with multiple CTE
;WITH JobTransactionsSumTypes AS
(
SELECT
[Job],
[Cost_Code],
SUM(CASE WHEN [Transaction_Type] = 'AP cost' AND [Commitment] <>'' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS APcostAmountComSum,
SUM(CASE WHEN [Transaction_Type] = 'AP cost' AND [Commitment] ='' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS APcostAmountNonComSum,
SUM(CASE WHEN [Transaction_Type] = 'Approved est changes' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS ApprovedEstChangesAmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Aprvd cmmtt cst chng' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS AprvdCmmttCstChngAmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Aprvd schdl val chn' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS AprvdSchdlValChnAmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Cash receipt' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS CashReceiptAmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Committed cost' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS CommittedCostAmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Dollars paid' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS DollarsPaidAmountSum,
SUM(CASE WHEN [Transaction_Type] = 'General Ledger only' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS GeneralLedgerOnlyAmountSum,
SUM(CASE WHEN [Transaction_Type] = 'JC cost' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS JCcostAmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Misc worksheet 1' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS MiscWorksheet1AmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Misc worksheet 2' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS MiscWorksheet2AmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Misc worksheet 3' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS MiscWorksheet3AmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Misc worksheet 4' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS MiscWorksheet4AmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Original estimate' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS OriginalEstimateAmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Pending est changes' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS PendingEstChangesAmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Percent complete' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS PercentCompleteAmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Pndng cmmtt cst chng' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS PndngCmmttCstChngAmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Pndng schd val chg 2' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS PndngSchdValChg2AmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Pndng schd val chg 3' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS PndngSchdValChg3AmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Pndng schdl val chng' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS PndngSchdlValChngAmountSum,
SUM(CASE WHEN [Transaction_Type] = 'PR cost' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS PRcostAmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Receivable Adjstment' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS ReceivableAdjstmentAmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Retention billed' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS RetentionBilledAmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Scheduled value' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS ScheduledValueAmountSum,
SUM(CASE WHEN [Transaction_Type] = 'Work Billed' THEN [Amount]-[Noncosted_Tax] ELSE 0 END) AS WorkBilledAmountSum
FROM [ADCData_Doric].[dbo].[JCT_CURRENT__TRANSACTION]
--WHERE your_condition
GROUP BY
[Job],
[Cost_Code]
), JobTransactionsSumTypes_Query2 AS
(
SELECT
APM_MASTER__DISTRIBUTION.Job
, APM_MASTER__DISTRIBUTION.Cost_Code
,SUM(CASE WHEN APM_MASTER__DISTRIBUTION.Onhold_Status <>0 THEN JCT_CURRENT__TRANSACTION.Amount-JCT_CURRENT__TRANSACTION.Noncosted_Tax ELSE 0 END) AS OnHoldAmount
,SUM(CASE WHEN APM_MASTER__DISTRIBUTION.Onhold_Status =0 THEN JCT_CURRENT__TRANSACTION.Amount-JCT_CURRENT__TRANSACTION.Noncosted_Tax ELSE 0 END) AS NotOnHoldAmount
FROM
dbo.JCT_CURRENT__TRANSACTION JCT_CURRENT__TRANSACTION
LEFT OUTER JOIN dbo.APM_MASTER__DISTRIBUTION APM_MASTER__DISTRIBUTION
ON JCT_CURRENT__TRANSACTION.Vendor = APM_MASTER__DISTRIBUTION.Vendor AND JCT_CURRENT__TRANSACTION.Invoice = APM_MASTER__DISTRIBUTION.Invoice AND JCT_CURRENT__TRANSACTION.Dist_Sequence = APM_MASTER__DISTRIBUTION.Dist_Seq
GROUP BY
APM_MASTER__DISTRIBUTION.Job
,APM_MASTER__DISTRIBUTION.Cost_Code
)
SELECT
Job,
Cost_Code,
APcostAmountComSum,
APcostAmountNonComSum,
ApprovedEstChangesAmountSum,
AprvdCmmttCstChngAmountSum,
AprvdSchdlValChnAmountSum,
CashReceiptAmountSum,
CommittedCostAmountSum,
DollarsPaidAmountSum,
GeneralLedgerOnlyAmountSum,
JCcostAmountSum,
MiscWorksheet1AmountSum,
MiscWorksheet2AmountSum,
MiscWorksheet3AmountSum,
MiscWorksheet4AmountSum,
OriginalEstimateAmountSum,
PendingEstChangesAmountSum,
PercentCompleteAmountSum,
PndngCmmttCstChngAmountSum,
PndngSchdValChg2AmountSum,
PndngSchdValChg3AmountSum,
PndngSchdlValChngAmountSum,
PRcostAmountSum,
ReceivableAdjstmentAmountSum,
RetentionBilledAmountSum,
ScheduledValueAmountSum,
WorkBilledAmountSum,
(ScheduledValueAmountSum) AS StartContractAmount,
(AprvdSchdlValChnAmountSum) AS ApprovedVariations,
(OriginalEstimateAmountSum + ApprovedEstChangesAmountSum + PendingEstChangesAmountSum) AS TotalBudgetOriginalApprovedPending,
(OriginalEstimateAmountSum + ApprovedEstChangesAmountSum)*(MiscWorksheet1AmountSum/100)+(PendingEstChangesAmountSum*(MiscWorksheet2AmountSum/100)) AS TotalCommitmentsBudget,
(CommittedCostAmountSum + AprvdCmmttCstChngAmountSum + PndngCmmttCstChngAmountSum) AS ApprovedPendingCommitedCosts,
j2.OnHoldAmount,
j2.NotOnHoldAmount
FROM
[JobTransactionsSumTypes] j1 LEFT OUTER JOIN JobTransactionsSumTypes_Query2 j2
ON j1.Job = j2.Job AND j1.Cost_Code = j2.Cost_Code
Got this error and facing a bit because the alias but my head just turning around with stuffs, could you help me to solve the alias wrong check this
SELECT B.PARTS_NO, B.Adj_Date, B.COST, B.ADJ_DESC, ADJ_FG_QTY_PREV = SUM(B.ADJ_FG_QTY_PREV), ADJ_COGS_QTY_PREV = SUM(B.ADJ_COGS_QTYPREV) , ADJ_FG_QTY = SUM(B.ADJ_FG_QTY), ADJ_COGS_QTY = SUM(B.ADJ_COGS_QTY)
FROM
(
SELECT
PARTS_NO=a.PARTS_NO,
Adj_Date=Convert(varchar(10),a.PROCESSING_DATETIME,105),
COST=ISNULL((SELECT CASE WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=1 THEN ISNULL(a.ECOST_01,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=2 THEN ISNULL(a.ECOST_02,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=3 THEN ISNULL(a.ECOST_03,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=4 THEN ISNULL(a.ECOST_04,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=5 THEN ISNULL(a.ECOST_05,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=6 THEN ISNULL(a.ECOST_06,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=7 THEN ISNULL(a.ECOST_07,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=8 THEN ISNULL(a.ECOST_08,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=9 THEN ISNULL(a.ECOST_09,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=10 THEN ISNULL(a.ECOST_10,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=11 THEN ISNULL(a.ECOST_11,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=12 THEN ISNULL(a.ECOST_12,0)
ELSE 0
END
FROM TITEMBALANCE a
WHERE a.[YEAR]=YEAR(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))
AND a.PARTS_NO=a.PARTS_NO),0),
ADJ_DESC ='CATS',
ADJ_FG_QTY_PREV=SUM(CASE WHEN Convert(numeric(6,0),Convert(varchar(6),a.PROCESSING_DATETIME,112))<>ISNULL(a.COSTING1,0) THEN (CASE WHEN Left(Ltrim(b.REASON_CODE),1)='1' THEN b.QUANTITY_F Else 0 End) else 0 end),
ADJ_COGS_QTYPREV=SUM(CASE WHEN Convert(numeric(6,0),Convert(varchar(6),a.PROCESSING_DATETIME,112))<>ISNULL(a.COSTING1,0) THEN (CASE WHEN Left(Ltrim(b.REASON_CODE),1)='2' THEN b.QUANTITY_F Else 0 End) else 0 end),
ADJ_FG_QTY=SUM(CASE WHEN Convert(numeric(6,0),Convert(varchar(6),a.PROCESSING_DATETIME,112))=ISNULL(a.COSTING1,0) THEN (CASE WHEN Left(Ltrim(b.REASON_CODE),1)='1' THEN b.QUANTITY_F Else 0 End) else 0 end),
ADJ_COGS_QTY=SUM(CASE WHEN Convert(numeric(6,0),Convert(varchar(6),a.PROCESSING_DATETIME,112))=ISNULL(a.COSTING1,0) THEN (CASE WHEN Left(Ltrim(b.REASON_CODE),1)='2' THEN b.QUANTITY_F Else 0 End) else 0 end)
FROM TPARTADJUSTMENTC a INNER JOIN TPARTADJUSTMENTCL b ON a.CARD_NO=b.CARD_NO AND a.INHOUSE_OUTSIDE=b.INHOUSE_OUTSIDE AND a.PARTS_NO=b.PARTS_NO AND a.PROCESS_CODE=b.PROCESS_CODE AND a.FILLER=b.FILLER AND a.PROCESSING_DATETIME=b.PROCESSING_DATETIME
WHERE ISNULL(a.COSTING1,0)=Convert(numeric(6,0),#Period)
GROUP BY a.PARTS_NO,Convert(varchar(10),a.PROCESSING_DATETIME,105),Left(Ltrim(b.REASON_CODE),1)
UNION ALL
SELECT
PARTS_NO=a.PARTS_NO,
Adj_Date=Convert(varchar(10),a.PROCESSING_DATETIME,105),
COST=ISNULL((SELECT CASE WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=1 THEN ISNULL(a.ECOST_01,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=2 THEN ISNULL(a.ECOST_02,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=3 THEN ISNULL(a.ECOST_03,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=4 THEN ISNULL(a.ECOST_04,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=5 THEN ISNULL(a.ECOST_05,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=6 THEN ISNULL(a.ECOST_06,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=7 THEN ISNULL(a.ECOST_07,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=8 THEN ISNULL(a.ECOST_08,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=9 THEN ISNULL(a.ECOST_09,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=10 THEN ISNULL(a.ECOST_10,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=11 THEN ISNULL(a.ECOST_11,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=12 THEN ISNULL(a.ECOST_12,0)
ELSE 0
END
FROM TITEMBALANCE a
WHERE a.[YEAR]=YEAR(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))
AND a.PARTS_NO=a.PARTS_NO),0),
ADJ_DESC ='IMPULSE',
ADJ_FG_QTYPREV=SUM(CASE WHEN Convert(numeric(6,0),Convert(varchar(6),a.PROCESSING_DATETIME,112))<>ISNULL(a.COSTING1,0) THEN (CASE WHEN Left(Ltrim(b.REASON_CODE),1)='1' THEN b.QUANTITY_F Else 0 End) else 0 end),
ADJ_COGS_QTYPREV=SUM(CASE WHEN Convert(numeric(6,0),Convert(varchar(6),a.PROCESSING_DATETIME,112))<>ISNULL(a.COSTING1,0) THEN (CASE WHEN Left(Ltrim(b.REASON_CODE),1)='2' THEN b.QUANTITY_F Else 0 End) else 0 end),
ADJ_FG_QTY=SUM(CASE WHEN Convert(numeric(6,0),Convert(varchar(6),a.PROCESSING_DATETIME,112))=ISNULL(a.COSTING1,0) THEN (CASE WHEN Left(Ltrim(b.REASON_CODE),1)='1' THEN b.QUANTITY_F Else 0 End) else 0 end),
ADJ_COGS_QTY=SUM(CASE WHEN Convert(numeric(6,0),Convert(varchar(6),a.PROCESSING_DATETIME,112))=ISNULL(a.COSTING1,0) THEN (CASE WHEN Left(Ltrim(b.REASON_CODE),1)='2' THEN b.QUANTITY_F Else 0 End) else 0 end)
FROM TPARTADJUSTMENTI a INNER JOIN TPARTADJUSTMENTIL b ON a.CARD_NO=b.CARD_NO AND a.INHOUSE_OUTSIDE=b.INHOUSE_OUTSIDE AND a.PARTS_NO=b.PARTS_NO AND a.PROCESS_CODE=b.PROCESS_CODE AND a.FILLER=b.FILLER AND a.PROCESSING_DATETIME=b.PROCESSING_DATETIME
WHERE ISNULL(a.COSTING1,0)=Convert(numeric(6,0),#Period)
GROUP BY a.PARTS_NO,Convert(varchar(10),a.PROCESSING_DATETIME,105),Left(Ltrim(b.REASON_CODE),1)
) B GROUP BY B.PARTS_NO, B.Adj_Date, B.COST, B.ADJ_DESC
You are using the alias a for both TITEMBALANCE in the subquery and TPARTADJUSTMENTC in the query.
I think that the condition a.PARTS_NO=a.PARTS_NO is supposed to compare fields from both tables, but because of the conflicting aliases it will just compare a field to itself and the query will return all parts. That will make the subquery return more than one record, and you get that error message.
This might help the answer, I changed 2 name alias between 2 union. Thanks everyone
SELECT #ProsesPeriode as TanggalPeriod , B.PARTS_NO, B.Adj_Date, B.COST, B.ADJ_DESC, ADJ_FG_QTY_PREV = SUM(B.ADJ_FG_QTY_PREV), ADJ_COGS_QTY_PREV = SUM(B.ADJ_COGS_QTYPREV) , ADJ_FG_QTY = SUM(B.ADJ_FG_QTY), ADJ_COGS_QTY = SUM(B.ADJ_COGS_QTY)
FROM
(
SELECT
PARTS_NO=d.PARTS_NO,
Adj_Date=Convert(varchar(10),d.PROCESSING_DATETIME,105),
COST=ISNULL((SELECT CASE WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=1 THEN ISNULL(a.ECOST_01,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=2 THEN ISNULL(a.ECOST_02,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=3 THEN ISNULL(a.ECOST_03,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=4 THEN ISNULL(a.ECOST_04,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=5 THEN ISNULL(a.ECOST_05,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=6 THEN ISNULL(a.ECOST_06,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=7 THEN ISNULL(a.ECOST_07,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=8 THEN ISNULL(a.ECOST_08,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=9 THEN ISNULL(a.ECOST_09,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=10 THEN ISNULL(a.ECOST_10,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=11 THEN ISNULL(a.ECOST_11,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=12 THEN ISNULL(a.ECOST_12,0)
ELSE 0
END
FROM TITEMBALANCE a
WHERE a.[YEAR]=YEAR(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))
AND a.PARTS_NO=d.PARTS_NO),0),
ADJ_DESC ='CATS',
ADJ_FG_QTY_PREV=SUM(CASE WHEN Convert(numeric(6,0),Convert(varchar(6),d.PROCESSING_DATETIME,112))<>ISNULL(d.COSTING1,0) THEN (CASE WHEN Left(Ltrim(b.REASON_CODE),1)='1' THEN b.QUANTITY_F Else 0 End) else 0 end),
ADJ_COGS_QTYPREV=SUM(CASE WHEN Convert(numeric(6,0),Convert(varchar(6),d.PROCESSING_DATETIME,112))<>ISNULL(d.COSTING1,0) THEN (CASE WHEN Left(Ltrim(b.REASON_CODE),1)='2' THEN b.QUANTITY_F Else 0 End) else 0 end),
ADJ_FG_QTY=SUM(CASE WHEN Convert(numeric(6,0),Convert(varchar(6),d.PROCESSING_DATETIME,112))=ISNULL(d.COSTING1,0) THEN (CASE WHEN Left(Ltrim(b.REASON_CODE),1)='1' THEN b.QUANTITY_F Else 0 End) else 0 end),
ADJ_COGS_QTY=SUM(CASE WHEN Convert(numeric(6,0),Convert(varchar(6),d.PROCESSING_DATETIME,112))=ISNULL(d.COSTING1,0) THEN (CASE WHEN Left(Ltrim(b.REASON_CODE),1)='2' THEN b.QUANTITY_F Else 0 End) else 0 end)
FROM TPARTADJUSTMENTC d INNER JOIN TPARTADJUSTMENTCL b ON d.CARD_NO=b.CARD_NO AND d.INHOUSE_OUTSIDE=b.INHOUSE_OUTSIDE AND d.PARTS_NO=b.PARTS_NO AND d.PROCESS_CODE=b.PROCESS_CODE AND d.FILLER=b.FILLER AND d.PROCESSING_DATETIME=b.PROCESSING_DATETIME
WHERE ISNULL(d.COSTING1,0)=Convert(numeric(6,0),#Period)
GROUP BY d.PARTS_NO,Convert(varchar(10),d.PROCESSING_DATETIME,105),Left(Ltrim(b.REASON_CODE),1)
UNION ALL
SELECT
PARTS_NO=k.PARTS_NO,
Adj_Date=Convert(varchar(10),k.PROCESSING_DATETIME,105),
COST=ISNULL((SELECT CASE WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=1 THEN ISNULL(a.ECOST_01,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=2 THEN ISNULL(a.ECOST_02,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=3 THEN ISNULL(a.ECOST_03,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=4 THEN ISNULL(a.ECOST_04,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=5 THEN ISNULL(a.ECOST_05,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=6 THEN ISNULL(a.ECOST_06,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=7 THEN ISNULL(a.ECOST_07,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=8 THEN ISNULL(a.ECOST_08,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=9 THEN ISNULL(a.ECOST_09,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=10 THEN ISNULL(a.ECOST_10,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=11 THEN ISNULL(a.ECOST_11,0)
WHEN MONTH(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))=12 THEN ISNULL(a.ECOST_12,0)
ELSE 0
END
FROM TITEMBALANCE a
WHERE a.[YEAR]=YEAR(Convert(Datetime,LTRIM(RTRIM(#Period))+'01',112))
AND a.PARTS_NO=k.PARTS_NO),0),
ADJ_DESC ='IMPULSE',
ADJ_FG_QTYPREV=SUM(CASE WHEN Convert(numeric(6,0),Convert(varchar(6),k.PROCESSING_DATETIME,112))<>ISNULL(k.COSTING1,0) THEN (CASE WHEN Left(Ltrim(b.REASON_CODE),1)='1' THEN b.QUANTITY_F Else 0 End) else 0 end),
ADJ_COGS_QTYPREV=SUM(CASE WHEN Convert(numeric(6,0),Convert(varchar(6),k.PROCESSING_DATETIME,112))<>ISNULL(k.COSTING1,0) THEN (CASE WHEN Left(Ltrim(b.REASON_CODE),1)='2' THEN b.QUANTITY_F Else 0 End) else 0 end),
ADJ_FG_QTY=SUM(CASE WHEN Convert(numeric(6,0),Convert(varchar(6),k.PROCESSING_DATETIME,112))=ISNULL(k.COSTING1,0) THEN (CASE WHEN Left(Ltrim(b.REASON_CODE),1)='1' THEN b.QUANTITY_F Else 0 End) else 0 end),
ADJ_COGS_QTY=SUM(CASE WHEN Convert(numeric(6,0),Convert(varchar(6),k.PROCESSING_DATETIME,112))=ISNULL(k.COSTING1,0) THEN (CASE WHEN Left(Ltrim(b.REASON_CODE),1)='2' THEN b.QUANTITY_F Else 0 End) else 0 end)
FROM TPARTADJUSTMENTI k INNER JOIN TPARTADJUSTMENTIL b ON k.CARD_NO=b.CARD_NO AND k.INHOUSE_OUTSIDE=b.INHOUSE_OUTSIDE AND k.PARTS_NO=b.PARTS_NO AND k.PROCESS_CODE=b.PROCESS_CODE AND k.FILLER=b.FILLER AND k.PROCESSING_DATETIME=b.PROCESSING_DATETIME
WHERE ISNULL(k.COSTING1,0)=Convert(numeric(6,0),#Period)
GROUP BY k.PARTS_NO,Convert(varchar(10),k.PROCESSING_DATETIME,105),Left(Ltrim(b.REASON_CODE),1)
) B GROUP BY B.PARTS_NO, B.Adj_Date, B.COST, B.ADJ_DESC
The root cause of your problem with this query is actually conflicting Aliases for Tables ItemBalance & TPartAdjustmentC.
The Same Alias (a) being used for the tables in the union All renders the condition comparing the part numbers as ambiguous.
I use IBM DB2 SQL.
Here is my current query:
select
EXSHPE as "Shape",
EXDLVY as "Delivery",
Sum(Case When EXSURF = 'Print' Then EXRLTO Else 0 End) As Retail_Print,
Sum(Case When EXSURF = 'Pattern' Then EXRLTO Else 0 End) as Retail_Pattern,
Sum(Case When EXSURF = 'Solid' Then EXRLTO Else 0 End) As Retail_Solid,
Sum(Case When EXSURF = 'UnknownA' Then EXRLTO Else 0 End) as Retail_UnknownA,
Sum(Case When EXSURF = 'UnknownB' Then EXRLTO Else 0 End) As Retail_UnknownB,
Sum(Case When EXSURF = 'UnknownC' Then EXRLTO Else 0 End) as Retail_UnknownC,
Sum(Case When EXSURF = 'Print' Then EXWHLO Else 0 End) As Wholesale_Print,
Sum(Case When EXSURF = 'Pattern' Then EXWHLO Else 0 End) as Wholesale_Pattern,
Sum(Case When EXSURF = 'Solid' Then EXWHLO Else 0 End) As Wholesale_Solid,
Sum(Case When EXSURF = 'UnknownA' Then EXWHLO Else 0 End) as Wholesale_UnknownA,
Sum(Case When EXSURF = 'UnknownB' Then EXWHLO Else 0 End) As Wholesale_UnknownB,
Sum(Case When EXSURF = 'UnknownC' Then EXWHLO Else 0 End) as Wholesale_UnknownC,
Sum(Case When EXSURF = 'Print' Then EXUNTO Else 0 End) As Units_Print,
Sum(Case When EXSURF = 'Pattern' Then EXUNTO Else 0 End) as Units_Pattern,
Sum(Case When EXSURF = 'Solid' Then EXUNTO Else 0 End) As Units_Solid,
Sum(Case When EXSURF = 'UnknownA' Then EXUNTO Else 0 End) as Units_UnknownA,
Sum(Case When EXSURF = 'UnknownB' Then EXUNTO Else 0 End) As Units_UnknownB,
Sum(Case When EXSURF = 'UnknownC' Then EXUNTO Else 0 End) as Units_UnknownC,
Sum(Case When EXSURF = 'Print' Then EXAURA Else 0 End) As Actual_AUR_Print,
Sum(Case When EXSURF = 'Pattern' Then EXAURA Else 0 End) as Actual_AUR_Pattern,
Sum(Case When EXSURF = 'Solid' Then EXAURA Else 0 End) As Actual_AUR_Solid,
Sum(Case When EXSURF = 'UnknownA' Then EXAURA Else 0 End) as Actual_AUR_UnknownA,
Sum(Case When EXSURF = 'UnknownB' Then EXAURA Else 0 End) As Actual_AUR_UnknownB,
Sum(Case When EXSURF = 'UnknownC' Then EXAURA Else 0 End) as Actual_AUR_UnknownC,
Sum(Case When EXSURF = 'Print' Then EXMERA Else 0 End) As Merch_AUR_Print,
Sum(Case When EXSURF = 'Pattern' Then EXMERA Else 0 End) as Merch_AUR_Pattern,
Sum(Case When EXSURF = 'Solid' Then EXMERA Else 0 End) As Merch_AUR_Solid,
Sum(Case When EXSURF = 'UnknownA' Then EXMERA Else 0 End) as Merch_AUR_UnknownA,
Sum(Case When EXSURF = 'UnknownB' Then EXMERA Else 0 End) As Merch_AUR_UnknownB,
Sum(Case When EXSURF = 'UnknownC' Then EXMERA Else 0 End) as Merch_AUR_UnknownC
from EXOWMSPD
Where (EXCO || '/' || EXDIV) = ?
Group By
EXSHPE,
EXDLVY
Order By
EXSHPE DESC,
EXDLVY DESC
Database looks like this:
I need to pivot of Surface, but dynamically.
The issue is, I only know the first 3 surface descriptions. But I need to be ready for up to 6.
Is there a way I could pivot this dynamically to grab the first 6 surfaces.
Example,
RETAIL_DOLLARS_1 10.00
RETAIL_DOLLARS_2 20.00
RETAIL_DOLLARS_3 50.00
RETAIL_DOLLARS_4 0.00
RETAIL_DOLLARS_5 0.00
RETAIL_DOLLARS_6 0.00
In this example, data was found for 3 surfaces, the other 3 I want filled with 0s.
I'm using this to make a report and I'll hide columns which will have SURFACE_DESCRIPTION_X equal to "".
Is there a way to do this?
Thanks
If you would like to cube the data on the various dimensions, try the
GROUP BY CUBE
clause