Update table with rolling average from itself - sql

I'm trying to update a temp table with a rolling average calculation (MS Access 2010.)
As a select query, this works to calculate a 3 month rolling average but is slow so I'd rather have the values stored and updated only when necessary:
SELECT tempQORDistGrouped.Type, tempQORDistGrouped.Supplier, tempQORDistGrouped.DepBkMo, tempQORDistGrouped.Amt, tempQORDistGrouped.Brands, tempQORDistGrouped.T2, tempQORDistGrouped.Brand, (select avg(rolavg.Amt) from tempQORDistGrouped as rolavg
where rolavg.Type = tempQORDistGrouped.Type
and rolavg.Supplier = tempQORDistGrouped.Supplier
and rolavg.Brands = tempQORDistGrouped.Brands
and rolavg.Brand = tempQORDistGrouped.Brand
and rolavg.DepBkMo between dateadd("m",-2,tempQORDistGrouped.DepBkMo) and tempQORDistGrouped.depbkmo) AS AvgAmt
FROM tempQORDistGrouped;
I've tried the update query below but I think my inner join syntax is bad as it won't recognize x1.Type as a valid field (do I need to include these as part of the inner join fields rather than in the where clause??):
UPDATE tempQORDistGrouped AS x1
INNER JOIN (SELECT itmID, avg(Amt) AS RolAvg
FROM tempQORDistGrouped
WHERE tempQORDistGrouped.Type = x1.Type
AND tempQORDistGrouped.Brand = x1.Brand
AND tempQORDistGrouped.Brands = x1.Brands
AND tempQORDistGrouped.T2 = x1.T2
AND tempQORDistGrouped.DepBkMo between dateadd("m",-2,x1.DepBkMo) and x1.DepBkMo
GROUP BY itmID
) AS x2
ON x1.itmID = x2.itmID
SET x1.3MonthRollingAmt = x2.RolAvg;
Cheers

Untested but should work.
I am doing a column level query to calculated the AVG and then mapping it back to the rest of the columns
Try this:
UPDATE tempQORDistGrouped AS x1
INNER JOIN (
SELECT itmID
, (
SELECT avg(Amt) amt
FROM tempQORDistGrouped x4
WHERE x4.Type = x3.Type
AND x4.Brand = x3.Brand
AND x4.Brands = x3.Brands
AND x4.T2 = x3.T2
AND x4.DepBkMo BETWEEN dateadd("m", - 2, x3.DepBkMo) AND x3.DepBkMo
) AS RolAvg
, x3.Brand
, x3.Brands
, x3.DepBkMo
, x3.T2
FROM tempQORDistGrouped x3
) AS x2
ON x1.itmID = x2.itmID
AND x1.Brand = x2.Brand
AND x1.Brands = x2.Brands
AND x1.T2 = x2.T2
AND x1.DepBkMo BETWEEN dateadd("m", - 2, x2.DepBkMo) AND x2.DepBkMo
SET x1.3MonthRollingAmt = x2.RolAvg;

Related

Get the sum of a count column in SQL

I have the following query
SELECT
dtc.coupon_type_company_name,
COUNT(*) * dtc.coupon_type_company_coupon_amount AS 'Total_Coupon_To_Be_Used',
dtc.coupon_type_company_coupon_months_combinable
FROM
[dbo].[coupon_type_Company_User] dtcu
JOIN
coupon_type_Company dtc ON dtcu.coupon_type_Company_ID = dtc.id
JOIN
person p ON dtcu.userID = p.userID
WHERE
coupon_type_company_coupon_is_combinable = 1
OR coupon_type_company_has_coupon = 1
AND dtc.companyID = 1081
AND p.is_active = 1
GROUP BY
dtc.coupon_type_company_name,dtc.coupon_type_company_coupon_amount,
dtc.coupon_type_company_coupon_months_combinable
This returns the following:
What I want to have however is just one column and one row that should take the SUM of my middle column (count(*)*dtc.coupon_type_company_coupon_amount).
How could I achieve this and prevent doing this in my code backend (C#)
You can wrap your query like this:
SELECT SUM(Total_Coupon_To_Be_Used) AS the_sum
FROM (
your query
) s
Use a "Table Expression", as in:
select sum(Total_Coupon_To_Be_Used) from (
SELECT dtc.coupon_type_company_name,
count(*) * dtc.coupon_type_company_coupon_amount as 'Total_Coupon_To_Be_Used',
dtc.coupon_type_company_coupon_months_combinable
FROM [dbo].[coupon_type_Company_User] dtcu
JOIN coupon_type_Company dtc ON dtcu.coupon_type_Company_ID = dtc.id
JOIN person p ON dtcu.userID = p.userID
WHERE coupon_type_company_coupon_is_combinable = 1
or coupon_type_company_has_coupon = 1
and dtc.companyID = 1081
AND p.is_active = 1
GROUP BY
dtc.coupon_type_company_name,dtc.coupon_type_company_coupon_amount,
dtc.coupon_type_company_coupon_months_combinable
) x

How to use alias of a subquery to get the running total?

I have a UNION of 3 tables for calculating some balance and I need to get the running SUM of that balance but I can't use PARTITION OVER, because I must do it with a sql query that can work in Access.
My problem is that I cannot use JOIN on an alias subquery, it won't work.
How can I use alias in a JOIN to get the running total?
Or any other way to get the SUM that is not with PARTITION OVER, because it does not exist in Access.
This is my code so far:
SELECT korisnik_id, imePrezime, datum, Dug, Pot, (Dug - Pot) AS Balance
FROM (
SELECT korisnik_id, k.imePrezime, r.datum, SUM(IIF(u.jedinstven = 1, r.cena, k.kvadratura * r.cena)) AS Dug, '0' AS Pot
FROM Racun r
INNER JOIN Usluge u ON r.usluga_id = u.ID
INNER JOIN Korisnik k ON r.korisnik_id = k.ID
WHERE korisnik_id = 1
AND r.zgrada_id = 1
AND r.mesec = 1
AND r.godina = 2017
GROUP BY korisnik_id, k.imePrezime, r.datum
UNION ALL
SELECT korisnik_id, k.imePrezime, rp.datum, SUM(IIF(u.jedinstven = 1, rp.cena, k.kvadratura * rp.cena)) AS Dug, '0' AS Pot
FROM RacunP rp
INNER JOIN Usluge u ON rp.usluga_id = u.ID
INNER JOIN Korisnik k ON rp.korisnik_id = k.ID
WHERE korisnik_id = 1
AND rp.zgrada_id = 1
AND rp.mesec = 1
AND rp.godina = 2017
GROUP BY korisnik_id, k.imePrezime, rp.datum
UNION ALL
SELECT uu.korisnik_id, k.imePrezime, uu.datum, '0' AS Dug, SUM(uu.iznos) AS Pot
FROM UnosUplata uu
INNER JOIN Korisnik k ON uu.korisnik_id = k.ID
WHERE korisnik_id = 1
GROUP BY uu.korisnik_id, k.imePrezime, uu.datum
) AS a
ORDER BY korisnik_id
You can save a query (let's name it Query1) for the UNION of the 3 tables and then create another query that returns each row in the first query and calculates the sum of the rows that are before it (optionally checking that they are in the same group).
It should be something like this:
SELECT *, (
SELECT SUM(Value) FROM Query1 AS b
WHERE b.GroupNumber=a.GroupNumber
AND b.Position<=a.Position
) AS RunningSum
FROM Query1 AS a
However, it's more efficient to do that in the report.

DAX SUM outside current context

This is my current data model ->
part of data model
I need help in creating a measure.
The measure I want to create should show the overall capacity of the ships that had trips in a time interval, as well as be able to see the total capacity based on the room type.
I am interested in obtaining the DAX equivalent of :
SELECT SUM(sc.capacity)
FROM Reporting.Trips t
JOIN Reporting.Dates d ON d.DateId = t.DateId
JOIN Reporting.ShipCapacities sc on sc.ShipId = t.ShipId
WHERE d.FiscalYear= 2017 AND d.FiscalWeek=15
OR per type
SELECT SUM(sc.capacity)
FROM Reporting.Trips t
JOIN Reporting.Dates d ON d.DateId = t.DateId
JOIN Reporting.ShipCapacities sc on sc.ShipId = t.ShipId
WHERE d.FiscalYear= 2017 AND d.FiscalWeek=15 and sc.CabinTypeId = 11
I tried to define a measure in this manner:
Total Rooms:=CALCULATE ( SUM ( 'Ship Capacities'[Ship Capacity] ) )
I have seen that this outputs the T-SQL equivalent of:
SELECT SUM(Capacity)
FROM
(
SELECT DISTINCT sc.*
FROM Reporting.Trips t
JOIN Reporting.Dates d ON d.DateId = t.DateId
JOIN Reporting.ShipCapacities sc on sc.ShipId = t.ShipId
WHERE d.FiscalYear= 2017 AND d.FiscalWeek=15
) x
OR per type
SELECT SUM(Capacity)
FROM
(
SELECT DISTINCT sc.*
FROM Reporting.Trips t
JOIN Reporting.Dates d ON d.DateId = t.DateId
JOIN Reporting.ShipCapacities sc on sc.ShipId = t.ShipId
WHERE d.FiscalYear= 2017 AND d.FiscalWeek=15 and sc.CabinTypeId = 11
) x
These are the query results ->Query results
Thanks.
This is the final measure that worked for me:
Total Rooms:=CALCULATE (
SUMX (
'Ship Capacities',
'Ship Capacities'[Ship Capacity]
* COUNTROWS ( FILTER ( Trips, AND( Trips[Sailed] = TRUE (),Trips[ShipId] = 'Ship Capacities'[ShipId] ) ))
)
)
Notice the COUNTROWS.
In the case of a many to one, then a one to many relation, it did not iterate (but previously I used SUM and not SUMX).
I found it unusual that I have to mention the relation between the many to many tables.
Otherwise it does not work.

Merge Source Table Into Target Table using subjoins

I am new to SQLDeveloper. Please help me in correcting the merge syntax.I want to merge the data from act_sl tavle into act_sls_0 table
I am using 2 joins in From Clause.
But I am Getting Errors :
Error(13,13): PL/SQL: ORA-00969: missing ON keyword
Error(4,1): PL/SQL: SQL Statement ignored
merge into act_sls_0 using(
( select * from
(select a_0.asp, gadim.uic as ga, pmm_styleid, week, colorcode , sizecode, storenum, units_asly,retail_asly,
cost_asly ,units_asregly,retail_asregly,units_asmkdly,retail_asmkdly,units_as_pln,retail_as_pln
from act_sls
join dimension w on w.externalkey = 'W'||substr(WEEK,3,2)||'_'||substr(WEEK,5,2)
join a_0 on ( w.externalkey between startweek and endweek)
join dimension strdim on strdim.externalkey = (case when length(storenum) <= 4 then RPAD('STR-', 8 - length(storenum), '0') else 'STR-' END) || storenum
join store_info_0 str on store = strdim.uic
join dimension gadim on gadim.externalkey = decode(store_type, 'RETAIL', 'GA-01', 'ECOM', 'GA-02', '')
where trendweeks < 6)t1
join(select distinct asp, product, ga, color, sstyl_shade, pmm_styleid from aplc_1 aplc
join apc_1 apc using (asp,product,color)
where activeitem = 1 and ga!=0 and color != 0)t2
on (t1.asp = t2.asp and
t1.pmm_styleid = t2.pmm_styleid
and (case when length(t1.colorcode) <= 4 then RPAD('SHD-', 8 - length(t1.colorcode), '0') else 'SHD-' END) || t1.colorcode = t2.sstyl_shade
and t1.ga = t2.ga))src
on (trg.asp = src.asp and trg.pmm_styleid = src.pmm_styleid and trg.colorcode = src.colorcode and trg.ga = src.ga)
when matched THEN
update SET
when matched THEN
update SET
trg.UNITS_ASLY = src.UNITS_ASLY,
trg.RETAIL_ASLY = src.RETAIL_ASLY,
trg.COST_ASLY = src.COST_ASLY,
trg.UNITS_ASREGLY = src.UNITS_ASREGLY,
trg.RETAIL_ASREGLY = src.RETAIL_ASREGLY,
trg.UNITS_ASMKDLY = src.UNITS_ASMKDLY,
trg.RETAIL_ASMKDLY = src.RETAIL_ASMKDLY,
trg.UNITS_AS_PLN = src.UNITS_AS_PLN,
trg.RETAIL_AS_PLN = src.RETAIL_AS_PLN
when not matched then insert
(trg.asp,trg.ga, trg.pmm_styleid, trg.colorcode,trg.sizecode,trg.storenum,trg.week,trg.UNITS_ASLY,trg.RETAIL_ASLY ,trg.COST_ASLY , trg.UNITS_ASREGLY ,trg.RETAIL_ASREGLY ,
trg.UNITS_ASMKDLY ,trg.RETAIL_ASMKDLY ,trg.UNITS_AS_PLN ,trg.RETAIL_AS_PLN )
values
(src.asp,src.ga, src.pmm_styleid, src.colorcode,src.sizecode,src.storenum,src.week,src.UNITS_ASLY,src.RETAIL_ASLY,src.COST_ASLY,src.UNITS_ASREGLY,
src.RETAIL_ASREGLY, src.UNITS_ASMKDLY, src.RETAIL_ASMKDLY, src.UNITS_AS_PLN, src.RETAIL_AS_PLN);
The format for a merge statement is:
merge into <target_table> tgt
using <table_name or subquery> src
on (<join conditions between the target and source datasets>)
when matched then
update set ...
when not matched then
insert (...)
values (...);
Quite apart from the fact that your source subquery is incorrect (there are errors around where the t1 and t2 are; too many brackets, inappropriately trying to alias something etc), whilst you have join conditions inside your subquery, you're completely missing the ON clause for the merge itself.
You need to define the join conditions that match the data returned by your source subquery to your target table.
Now the error is : src.ga - Invalid Identifier
Although I have ga table in Trg table and src table .
merge into act_sls_0 trg using( select * from
(select a_0.asp, gadim.uic as ga, pmm_styleid, week, colorcode , sizecode, storenum, units_asly,retail_asly,
cost_asly ,units_asregly,retail_asregly,units_asmkdly,retail_asmkdly,units_as_pln,retail_as_pln
from act_sls
join dimension w on w.externalkey = 'W'||substr(WEEK,3,2)||'_'||substr(WEEK,5,2)
join a_0 on ( w.externalkey between startweek and endweek)
join dimension strdim on strdim.externalkey = (case when length(storenum) <= 4 then RPAD('STR-', 8 - length(storenum), '0') else 'STR-' END) || storenum
join store_info_0 str on store = strdim.uic
join dimension gadim on gadim.externalkey = decode(store_type, 'RETAIL', 'GA-01', 'ECOM', 'GA-02', '')
where trendweeks < 6)t1
join(select distinct asp, product, ga, color, sstyl_shade, pmm_styleid from aplc_1 aplc
join apc_1 apc using (asp,product,color)
where activeitem = 1 and ga!=0 and color != 0)t2
on (t1.asp = t2.asp and
t1.pmm_styleid = t2.pmm_styleid
and (case when length(t1.colorcode) <= 4 then RPAD('SHD-', 8 - length(t1.colorcode), '0') else 'SHD-' END) || t1.colorcode = t2.sstyl_shade
and t1.ga = t2.ga))src
on (trg.asp = src.asp and trg.pmm_styleid = src.pmm_styleid and trg.colorcode = src.colorcode and trg.ga = src.ga)
when matched THEN
update SET
trg.UNITS_ASLY = src.UNITS_ASLY,
trg.RETAIL_ASLY = src.RETAIL_ASLY,
trg.COST_ASLY = src.COST_ASLY,
trg.UNITS_ASREGLY = src.UNITS_ASREGLY,
trg.RETAIL_ASREGLY = src.RETAIL_ASREGLY,
trg.UNITS_ASMKDLY = src.UNITS_ASMKDLY,
trg.RETAIL_ASMKDLY = src.RETAIL_ASMKDLY,
trg.UNITS_AS_PLN = src.UNITS_AS_PLN,
trg.RETAIL_AS_PLN = src.RETAIL_AS_PLN
when not matched then insert
(trg.asp,trg.ga, trg.pmm_styleid, trg.colorcode,trg.sizecode,trg.storenum,trg.week,trg.UNITS_ASLY,trg.RETAIL_ASLY ,trg.COST_ASLY ,trg.UNITS_ASREGLY ,trg.RETAIL_ASREGLY ,
trg.UNITS_ASMKDLY ,trg.RETAIL_ASMKDLY ,trg.UNITS_AS_PLN ,trg.RETAIL_AS_PLN )
values
(src.asp,src.ga, src.pmm_styleid, src.colorcode,src.sizecode,src.storenum,src.week,src.UNITS_ASLY,src.RETAIL_ASLY,src.COST_ASLY,src.UNITS_ASREGLY,
src.RETAIL_ASREGLY, src.UNITS_ASMKDLY, src.RETAIL_ASMKDLY, src.UNITS_AS_PLN, src.RETAIL_AS_PLN);
commit;

Postgres Update column with another rows data

Ok I have two tables
measures
attr_id, period, net_orders, ref_1 (key = attr_id,period)
and
policy
attr_id, lead_time
What I need to do is grab the 'net_orders' from measure at period (which is a date), Add the 'lead_time' and update the measure table 'ref_1' where period = period+lead
I currently have the select that gets me the data I need but I keep losing myself in my head when trying to figure out the where clauses.
SELECT
m.attr_id,
m.period,
m.net_orders,
p.lead_time,
DATE(m.period) + CAST(p.lead_time as INTEGER) as updateperiod
FROM
measures m
INNER JOIN policy p ON p.attr_id = m.attr_id
I am stuck with some of the following query - aka incomplete
UPDATE
measures m
SET
ref_1 = (SELECT m1.net_orders FROM measures m1
WHERE m1.attr_id = m.attr_id AND m1.period = m.period)
WHERE
attr_id = (SELECT m3.attr_id
FROM measures m3 WHERE m3.attr_id = m.attr_id
AND m3.period = m.period)
AND m.period = (SELECT DATE(m2.period) + CAST(p2.lead_time AS INTEGER)
FROM measures m2 INNER JOIN policy p2 ON p2.attr_id = m2.attr_id
WHERE m2.attr_id = m.attr_id AND m2.period = m.period)
EDIT
update measures m
set reference_1 = s.net_orders
from (
select
m.attribute_id, period, net_orders,
DATE(period) + CAST(lead_time as integer) as periodlevel
from
measures m
inner join policies p on p.attribute_id = m.attribute_id
) s
where
m.attribute_id = s.attribute_id
and m.period = s.periodlevel
This is the query that has ended up working. I was getting errors with first answer but looks like it is working now!
update measures m
set ref_1 = s.net_orders
from (
select
m.attr_id, period, net_orders,
period::date + lead_time::int period
from
measures m
inner join
policy using(attr_id)
) s
where
s.attr_id = m.attr_id
and s.period = m.period::date