I have this table
| ID_prim | ID (FKey) | Date | Moved Items |
|:-----------|:------------|-------------:|:------------:|
| 1003 | 12_1 | nov 2013 | 2 |
| 1003 | 12_2 | okt 2013 | 3 |
| 1003 | 12_3 | dec 2014 | 5 |
| 1003 | 12_4 | feb 2015 | 10 |
| 1003 | 12_5 | apr 2012 | 1 |
| 1003 | 12_11 | jan 2011 | 5 |
I want to query the same table as follows:
Order the Date by desc
Sum each 'Moved Item" per row
Stop the query if the Sum reaches my desired amount
My desired amount starts from the MAX 'Summed Total' (26) and subtracts the amount I want (16)
Like so
| ID_prim | ID (FKey) | Date | Moved Items | Summed Total |
|:-----------|:------------|-------------:|:------------:|:------------:|
| 1003 | 12_4 | feb 2015 | 10 | 26
| 1003 | 12_3 | dec 2014 | 5 | 16
| 1003 | 12_3 | nov 2013 | 2 | 11 <
| 1003 | 12_4 | okt 2013 | 3 | 9
| 1003 | 12_5 | apr 2012 | 1 | 6
| 1003 | 12_11 | jan 2011 | 5 | 5
I want to stop the query when i reach "Summed Total" (26) - 16 = 10. So Show me everything from 10 >
I would only get these values in the database.
| ID_prim | ID (FKey) | Date | Moved Items | Summed Total |
|:-----------|:------------|-------------:|:------------:|:------------:|
| 1003 | 12_4 | feb 2015 | 10 | 26
| 1003 | 12_3 | dec 2014 | 5 | 16
| 1003 | 12_3 | nov 2013 | 2 | 11
What I have is the following
SELECT
T1.ID_prim, T1.ID as ID (FKey), T1.Moved_Items as Moved Items, t1.Date, SUM(T2.MOVEMENTQTY) AS Summed Total
FROM Table1 T1
INNER JOIN Table1 T2 ON T2.ID <= T1.ID
inner join table2 inout on T1.ID_prim = inout.ID_prim
AND T2.ID_prim = inout.ID_prim
AND T2.ID_prim = T1.ID_prim
where t1.ID_prim = 1003
and t2.ID_prim = 1003
and inout.ISSOTRX = 'N'
GROUP BY T1.ID_prim, T1.Moved Items, t1.Date
HAVING SUM(T2.Moved Items) <= 16
order by t1.UPDATED desc
But the sum doesn't really work.
Can anyone help me out to make the SQL statement for Oracle DB that will print my Desired table?
Based on OP's clarifications via comments on the question, it could be done using SUM() analytic function to get the running total, and then filter it based on the condition.
Table:
SQL> SELECT * FROM t;
ID_PRIM ID DT MOVED
---------- ----- --------- ----------
1003 12_1 01-NOV-13 2
1003 12_2 01-OCT-13 3
1003 12_3 01-DEC-14 5
1003 12_4 01-FEB-15 10
1003 12_5 01-APR-12 1
1003 12_11 01-JAN-11 5
6 rows selected.
SQL>
Running total
SQL> SELECT t.*, SUM(moved) OVER(ORDER BY dt) sm FROM t ORDER BY dt DESC;
ID_PRIM ID DT MOVED SM
---------- ----- --------- ---------- ----------
1003 12_4 01-FEB-15 10 26
1003 12_3 01-DEC-14 5 16
1003 12_1 01-NOV-13 2 11
1003 12_2 01-OCT-13 3 9
1003 12_5 01-APR-12 1 6
1003 12_11 01-JAN-11 5 5
6 rows selected.
SQL>
Desired output
SQL> WITH DATA AS
2 ( SELECT t.*, SUM(moved) OVER(ORDER BY dt) sm FROM t ORDER BY dt DESC
3 )
4 SELECT * FROM data WHERE sm >= 16;
ID_PRIM ID DT MOVED SM
---------- ----- --------- ---------- ----------
1003 12_4 01-FEB-15 10 26
1003 12_3 01-DEC-14 5 16
SQL>
Please note that, nov 2013 is not a date, it is a string. Since you want to sort on the basis of date, you must always use TO_DATE to explicitly convert it into date. Anyway, I used TO_DATE to create the sample data.
Update OP wants to subtract his desired value from the MAX value of the summed up values at run time.
SQL> WITH DATA AS
2 ( SELECT t.*, SUM(moved) OVER(ORDER BY dt) sm FROM t ORDER BY dt DESC
3 )
4 SELECT * FROM DATA t WHERE sm >
5 (SELECT MAX(sm) FROM data
6 ) - 16 ;
ID_PRIM ID DT MOVED SM
---------- ----- --------- ---------- ----------
1003 12_4 01-FEB-15 10 26
1003 12_3 01-DEC-14 5 16
1003 12_1 01-NOV-13 2 11
SQL>
In the updated query, MAX(sm) returns 26, and then the rows are filtered on the condition WHERE sm > MAX(sm) -16 which means return all the rows where the 'sm' value is greater than 26 -16 i.e. 10. You could use a substitution variable to input the value 16 at run time.
Related
From the below table i want to write a select statement where i can select the price of the items for the
latest date.
Item | Price | Date
------|----------|--------
1001 | 10 | 26-5-2019
1001 | 11 | 15-02-2020
1001 | 9 | 28-08-2020
1002 | 5 | 1/7/2019
1002 | 3 | 8/11/2019
1002 | 4 | 5/5/2020
1003 | 6 | 26-05-2019
1003 | 7 | 1/2/2020
1003 | 5 | 15-09-2020
Result should be as below:
Item | Price | Date
------|----------|--------
1001 | 9 | 28-08-2020
1002 | 4 | 5/5/2020
1003 | 5 | 15-09-2020
Despite the fact that the table is unreadable and you haven't posted anything about what you have tried so far, I will try to help you...
You can get the price via Window Functions - in this case row_number. You should try something like the following:
SELECT x.*
FROM (SELECT Item, Price, [Date], ROW_NUMBER() OVER (PARTITION BY Item ORDER BY [Date] DESC) AS rn) x
WHERE x.rn = 1
SQL Newb here, I'm having a bit of trouble understanding this problem. How can I write a single SELECT statement where I can have columns with their own WHERE clauses, do a calculation, and group the results.
I can write the query to sum totals and do averages checks grouping by revenue center and fiscal year, but I can't quite grasp how to do side by side compare with a single query.
SALES DATA
| RevenueCenter | FiscalYear | TotalSales | NumChecks |
|---------------|------------|------------|-----------|
| market | 2019 | 2000.00 | 10 |
| restaurant | 2019 | 5000.00 | 25 |
| restaurant | 2020 | 4000.00 | 20 |
| market | 2020 | 3000.00 | 10 |
COMPARE REPORT
| RevenueCenter | TotalSales2020 | TotalSales2019 | %Change | AvgCheck2020 | AvgCheck2019 | %Change |
| market | 3000.00 | 2000.00 | +50% | 300.00 | 200.00 | +50% |
| restaurant | 4000.00 | 5000.00 | -20% | 200.00 | 200.00 | 0% |
Would this help? No big deal, just a self-join with some arithmetic.
SQL> with sales (revenuecenter, fiscalyear, totalsales, numchecks) as
2 -- sample data
3 (select 'market' , 2019, 2000, 10 from dual union all
4 select 'market' , 2020, 3000, 10 from dual union all
5 select 'restaurant', 2019, 5000, 25 from dual union all
6 select 'restaurant', 2020, 4000, 20 from dual
7 )
8 -- query you need
9 select a.revenuecenter,
10 b.totalsales totalsales2020,
11 a.totalsales totalsales2019,
12 --
13 (b.totalsales/a.totalsales) * 100 - 100 "%change totalsal",
14 --
15 b.totalsales / b.numchecks avgcheck2020,
16 a.totalsales / a.numchecks avgcheck2019,
17 --
18 (b.totalsales / b.numchecks) /
19 (a.totalsales / a.numchecks) * 100 - 100 "%change numcheck"
20 from sales a join sales b on a.revenuecenter = b.revenuecenter
21 and a.fiscalyear < b.fiscalyear;
REVENUECEN TOTALSALES2020 TOTALSALES2019 %change totalsal AVGCHECK2020 AVGCHECK2019 %change numcheck
---------- -------------- -------------- ---------------- ------------ ------------ ----------------
market 3000 2000 50 300 200 50
restaurant 4000 5000 -20 200 200 0
SQL>
I have a requirement for a table as shown below. As you can see mgt_year,tot_dflt_mgt and to_accum_mgt columns. In year column where its 2016 the value is 20 and accum value is 600. What I want is that when I do
(to_accum_mgt - tot_dflt_mgt)
I want this calculated result in previous row as shown in the table below. Then this calculated result i.e. 580 is used for subtracting 9 like (580 - 9) for year 2015 and so on for all trailing years. I have done this in excel and also in Oracle thanks to #mathguy, but how to achieve this result in SQL server. I have tried to use this SQL server but its not working.
Please forgive My bad English and noob formatting.
My table t:
line_seg MGT_YEAR TOT_DFLT_MGT TOT_ACCUM_MGT
--------- -------- ------------ ------------
A 2013 10
A 2014 15
A 2015 9
A 2016 20 600
B 2013 10
B 2014 15
B 2015 8
B 2016 20 500
Oracle Solution:
select mgt_year, tot_dflt_mgt,
max(tot_accum_mgt) over () -
nvl( sum(tot_dflt_mgt) over
(order by mgt_year
rows between 1 following and unbounded following)
, 0 ) as tot_accum_mgt
from t;
but I am unable use this in SQL Server.
required output
line_seg MGT_YEAR TOT_DFLT_MGT TOT_ACCUM_MGT
--------- -------- ------------ ------------
A 2013 10 556
A 2014 15 471
A 2015 9 580
A 2016 20 600
B 2013 12 457
B 2014 15 472
B 2015 8 480
B 2016 20 500
select *,
(sum(TOT_ACCUM_MGT) over()) -
(sum(TOT_DFLT_MGT ) over (order by TOT_DFLT_MGT )) as somecolname
from
table
Put Row_number() and self join it with the previous row on (a.ID = b.ID) and (a.row_num = b.row_num - 1)
OR
You can use lag() function
Please try the following query. I assumed that you are using 2012+ version of SQL Server. If not, please change the FIRST_VALUE to SUM -
SELECT t1.line_seg, t1.mgt_year, t1.[tot_dflt_mgt]
, FIRST_VALUE(t1.tot_accum_mgt) OVER(PARTITION BY t1.[line_seg] ORDER BY t1.mgt_year DESC)
- ISNULL(SUM(t2.[tot_dflt_mgt]) OVER(PARTITION BY t2.[line_seg] ORDER BY t2.mgt_year DESC), 0) AS tot_accum_mgt
FROM [dbo].[t] AS t1
LEFT JOIN [dbo].[t] AS t2 ON (t2.line_seg = t1.line_seg AND t2.mgt_year = t1.mgt_year + 1)
ORDER BY t1.line_seg, t1.mgt_year ASC;
To do this first I have to imagine the table as sorted by the descending order of date -
+------------+----------+--------------+---------------+
| line_seg | mgt_year | tot_dflt_mgt | tot_accum_mgt |
+------------+----------+--------------+---------------+
| A | 2016 | 20 | 600 |
| A | 2015 | 9 | NULL |
| A | 2014 | 15 | NULL |
| A | 2013 | 10 | NULL |
| B | 2016 | 20 | 500 |
| B | 2015 | 8 | NULL |
| B | 2014 | 15 | NULL |
| B | 2013 | 12 | NULL |
+------------+----------+--------------+---------------+
Then all I have to do is to subtract the PREVIOUS running total of tot_dflt_mgt from the latest year's tot_accum_mgt. This is equivalent to subtract the previous tot_dflt_mgt from the current computed value of tot_accum_mgt To use the previous year's fields LEFT JOIN is used to self join the table. Resulting in the following table -
+------------+----------+--------------+---------------+------------+----------+--------------+---------------+
| line_seg | mgt_year | tot_dflt_mgt | tot_accum_mgt | line_seg | mgt_year | tot_dflt_mgt | tot_accum_mgt |
+------------+----------+--------------+---------------+------------+----------+--------------+---------------+
| A | 2013 | 10 | NULL | A | 2014 | 15 | NULL |
| A | 2014 | 15 | NULL | A | 2015 | 9 | NULL |
| A | 2015 | 9 | NULL | A | 2016 | 20 | 600 |
| A | 2016 | 20 | 600 | NULL | NULL | NULL | NULL |
| B | 2013 | 12 | NULL | B | 2014 | 15 | NULL |
| B | 2014 | 15 | NULL | B | 2015 | 8 | NULL |
| B | 2015 | 8 | NULL | B | 2016 | 20 | 500 |
| B | 2016 | 20 | 500 | NULL | NULL | NULL | NULL |
+------------+----------+--------------+---------------+------------+----------+--------------+---------------+
The AND t2.mgt_year = t1.mgt_year + 1 filter in the LEFT join clause does the trick of getting previous rows value. Now all I had to do is to calculate the running total on this previous rows (t2). Also as, subtracting NULL from anything will result in NULL. So ISNULL replaces any NULL with zeros.
ISNULL(SUM(t2.[tot_dflt_mgt]) OVER(PARTITION BY t2.[line_seg] ORDER BY t2.mgt_year DESC), 0) AS tot_accum_mgt
Now, as we have the previous running total of tot_dflt_mgt, all we have to do is to delete the latest (largest mgt_year) tot_accum_mgt. We get that by using FIRST_VALUE function. SUM could also be used instead I guess.
FIRST_VALUE(t1.tot_accum_mgt) OVER(PARTITION BY t1.[line_seg] ORDER BY t1.mgt_year DESC)
I am using an Access front end screen and SQL queries at the back end. I am trying to get a result set that is grouped at 2 levels: Region & Month and then a relevant count of total clients active in that period, clients with orders and clients without orders all within the period selected by the user.
Below are the 2 tables in use
Client Table A
ID | Region | StartDate | Name
1 | North | 1 Jan 16 | ABC
2 | North | 1 Mar 16 | DEF
3 | East | 1 Jul 16 | GHE
4 | East | 1 Aug 16 | HIJ
5 | West | 1 Feb 16 | KLM
6 | West | 1 Mar 16 | NOP
7 | South | 1 Apr 16 | QUR
8 | South | 1 Jan 16 | STU
Orders Table B
OrderID | Client ID |Order Date
1 | 1 | 15 Mar 16
2 | 3 | 15 Jul 16
3 | 5 | 15 Jun 16
4 | 8 | 15 Jul 16
5 | 6 | 15 Jul 16
6 | 4 | 15 Jan 16
7 | 2 | 15 Feb 16
8 | 1 | 15 Jul 16
9 | 3 | 05 Aug 16
10 | 3 | 16 Jul 16
11 | 2 | 15 May 16
12 | 4 | 15 May 16
13 | 6 | 15 May 16
14 | 7 | 15 Mar 16
The User picks a start date and end date for the report for Eg 1 May 2016 to 31 Jul 16
I need a query that will evaluate if client start date is within reporting period and produce the following out put:
Result Set
Region | Month |Total Clients|Clients with Orders|Clients w/o Orders
North |May-2016| 2 | 1 | 1
North |Jun-2016| 2 | 0 | 2
North |Jul-2016| 2 | 1 | 1
East |May-2016| 0 | 0 | 0
East |Jun-2016| 0 | 0 | 0
East |Jul-2016| 1 | 1 | 0
West |May-2016| 2 | 1 | 1
West |Jun-2016| 2 | 0 | 2
West |Jul-2016| 2 | 1 | 1
South |May-2016| 2 | 0 | 2
South |Jun-2016| 2 | 0 | 2
South |Jul-2016| 2 | 1 | 1
Ive been stuck on this for 2 weeks now.. Please Help!!!
if it helps this is how far I have gotten
PARAMETERS startDt DateTime, endDt DateTime, loc Text ( 255 );
SELECT DISTINCT a.[Region] AS Region,
Format(b.[Orderdate],"MMM-YY") AS MonthOrder,
(Select Count(CMet.[clientID]) as cnt from
(SELECT distinct b.[orderID], Format(b.[order date],"MMM-YY")
as Contact_Month, a.[clientID], a.[Region]
FROM Client as a
INNER JOIN orders AS b ON a.[client ID] = b.[client id]
WHERE iif(isnull(loc),a.[REgion] like '*',instr (loc,a.[region]))
and (b.[orderdate] between startDt and endDt)
and (a.[Start date] < startDt)
GROUP BY a.[Region], Format(b.[order date],"MMM-YY"),
a.[clientID], a.[Region]
HAVING count(a.[clientID]) >=1) as CMet) AS Clients_Met,
(select count([client id]) from clients where
iif(isnull(loc),[region] like '*',instr (loc,[region])) and
client.[Start date] < startDt AS Total_Client,
(Total_Client-Clients_Met) AS Not_Met,
format(Clients_Met/iif(Total_Client =0,1,Total_Client),'##.##%') AS Met_Percentage
FROM clients AS a
INNER JOIN orders AS b ON a.[client ID]=b.[client id]
WHERE iif(isnull(loc),a.[region] like '*',instr (loc,a.[region]))
and (a.[Start date] < startDt
GROUP BY a.[region], Format(b.[order date],"MMM-YY")
HAVING count(a.[client id]) >=1
ORDER BY a.[region];
I tried the solution below. The idea is to do the grouping in the inner query, then do the summing in the outer one:
SELECT Region, Month, Count(ID) AS Clients, Sum(HasOrder) AS ClientsWithOrders,
[Clients]-[ClientsWithOrders] AS ClientsWithoutOrders
FROM (SELECT Region, CDate(Month([Order Date]) & "/1/" & Year([Order Date])) AS [Month],
ID, Max(IIf([Client ID]=[ID],1,0)) AS HasOrder
FROM Orders, Client
WHERE ((([Order Date])>=#5/1/2016# And
([Order Date])<DateAdd("d",1,#7/31/2016#)))
GROUP BY Region, CDate(Month([Order Date]) & "/1/" & Year([Order Date])), ID)
AS RegionMonthClient
GROUP BY Region, Month
The difficulty is I'm getting different results from you. For example, for East clients (3,4) I see one with an order in May (client 4) and one with an order in July (client 3).
Is this approach useful to you in any way?
You can use the join statement and to check the date use the BETWEEN operation. Here is the link for sample join statement and Between Opration.
I'm on Teradata. I have an order table like the below.
custID | orderID | month | order_amount
-----------------------------------------
1 | 1 | jan | 10
1 | 2 | jan | 20
1 | 3 | feb | 5
1 | 4 | feb | 7
2 | 5 | mar | 20
2 | 6 | apr | 30
I'd like to add a column to the above table called "Avg order amount per month per customer". Since the table is at an order level, adding this column will cause duplicates like the below, which is ok.
custID | orderID | month | order_amount | avgOrdAmtperMonth
-------------------------------------------------------------
1 | 1 | jan | 10 | 15
1 | 2 | jan | 20 | 15
1 | 3 | feb | 5 | 6
1 | 4 | feb | 7 | 6
2 | 5 | mar | 20 | 20
2 | 6 | apr | 30 | 30
I want the output to have all the columns above, not just the custid and the new column. I'm not sure how to write this because one part of the table is an at order level and the new column needs to be grouped by customer+month. How would I do this?
This is a simple group average:
AVG(order_amount) OVER (PARTITION BY custID, month)
Why not just do the calculation when you query the table?
select t.*,
avg(order_amount) over (partition by custId, month) as avgOrderAmtPerMonth
from t;
You can add this into a view if you want to make it available to multiple downstream queries.
Actually adding the column to the table is a maintenance "nightmare". You have to add triggers to the table and update the value for updates, inserts, and deletes.