fetching records for previous month - sql

item loc year month quantity startdate
XYZ A 2020 1 3 23-06-2020
ABC B 2020 2 218 24-06-2020
SDC C 2020 6 107 25-06-2020
QWE D 2020 7 144 25-06-2020
XYZ A 2019 12 89 23-06-2020
ABC B 2019 11 218 24-06-2020
SDC C 2020 5 117 25-06-2020
QWE D 2020 6 144 25-06-2020
if i consider the above table then my output should look like this:
item loc year month quantity startdate
XYZ A 2020 1 89 23-06-2020
ABC B 2020 2 3 24-06-2020
SDC C 2020 6 117 25-06-2020
QWE D 2020 7 144 25-06-2020
so u can see that only quantities values changed and that we are taking from previos months and rest columns values are as it is.

It looks like you want window function lag(). For your sample data, this would produce the desired results:
select *
from (
select
item,
loc,
year,
month,
lag(quantity) over(partition by item, loc order by year, month) quantity,
startdate
from mytable
) t
where quantity is not null

Consider query which works in Access database:
SELECT Table1.*, (SELECT TOP 1 quantity FROM Table1 AS Dupe
WHERE Dupe.item = Table1.item AND Dupe.loc = Table1.loc
AND DateSerial(Dupe.[Year],Dupe.[Month],1)<DateSerial(Table1.[Year],Table1.[Month],1)
ORDER BY DateSerial(Dupe.[Year],Dupe.[Month],1)) AS PrevQty
FROM Table1;
If you want to return 0 when there is a gap in month sequence, consider:
SELECT Table1.*, Nz((SELECT quantity FROM Table1 AS Dupe
WHERE Dupe.item = Table1.item AND Dupe.loc = Table1.loc
AND DateSerial(Dupe.[Year],Dupe.[Month],1)=DateAdd("m",-1,DateSerial(Table1.[Year],Table1.[Month],1))
ORDER BY DateSerial(Dupe.[Year],Dupe.[Month],1)),0) AS PrevQty
FROM Table1;
Or
SELECT Q1.*, Nz(Q2.quantity,0) AS PrevQty FROM (
SELECT Table1.*, DateSerial([Year],[Month],1) AS FD FROM Table1) AS Q1
LEFT JOIN (
SELECT Table1.*, DateAdd("m",+1,DateSerial([Year],[Month],1)) AS PD FROM Table1) AS Q2
ON Q1.FD=Q2.PD AND Q1.item=Q2.item and Q1.loc=Q2.loc;

Related

How to convert this SELECT Statement into a DELETE statement?

I want to delete all records with a particular id and category except the one with the max date in MS Access.
Edit:
This is how my Data looks like
id
category
date
1
1
24 June 2021
1
1
20 June 2021
1
2
25 June 2021
1
2
26 June 2021
2
1
24 June 2021
2
1
26 June 2021
And this is how i want my data to look like
id
category
date
1
1
24 June 2021
1
2
26 June 2021
2
1
26 June 2021
I have this SELECT statement to show me all records I want to keep:
Select
t1.*
From
table t1
inner join
(select max(date) as maxdate, id
from table
group by id) t2 on t1.id = t2.id
and t1.date = t2.maxdate
I can't figure out a Delete statement that works in Access.
You can use:
delete from t
where t.date < (select max(t2.date)
from t as t2
where t2.id = t.id and t2.category = t.category
);

PostgreSQL year-over-year growth

How can I calculate the year-over-year growth by country in PostgreSQL? I have a query which works reasonably well, but it also takes values from one country and compares it with those from another country, when the value for the first year should be null or zero.
Expected result:
year | country | value | yoy
2019 A 10 -0.66
2018 A 20 0.05
2017 A 19 null
2019 B 8 -0.22
2018 B 10 -0.66
2017 B 20 null
Current result:
year | country | value | yoy
2019 A 10 -0.66
2018 A 20 0.05
2017 A 19 0.81
2019 B 8 -0.22
2018 B 10 -0.66
2017 B 20 null
Query:
SELECT *,
- 100.0 * (1 - LEAD(value) OVER (ORDER BY t.country) / value) AS Grown
FROM tbl AS t
ORDER BY t.country
then get the lead() withing each country ordered by year:
SELECT *,
- 100.0 * (value - LEAD(value) OVER (Partition by Country ORDER BY t.year) / value) AS Growth
FROM tbl AS t
ORDER BY t.country
For monthly data:
SELECT current_table.item_id, current_table.date, (current_table.count - year_ago_table.count)/year_ago_table.count as count_year_over_year,
FROM
(SELECT table.item_id, table - INTERVAL '1 year' as year_ago_date, table.count FROM table) current_table
JOIN
(SELECT table.item_id, table.date, table.count FROM table) year_ago_table
ON current_table.item_id = year_ago_table.item_id AND
current_table.year_ago_date = year_ago_table.date
ORDER BY date DESC

Left outer join for multiple users

I have a database for rounds of golf. I want to see how many rounds each user has per month for the last year.
To do that I created this view last_12_months with this code
SELECT date_part('month'::text, dates.date) AS month,
date_part('year'::text, dates.date) AS year
FROM ( SELECT (generate_series((now() - '1 year'::interval), now(), '1 mon'::interval))::date AS date) dates;
month
year
1
2020
2
2020
and so on to ...
12
2020
The summary view for counting the rounds is very simple also rounds_count_by_users
user_id
month
year
count_all
1
1
2020
15
1
3
2020
12
1
5
2020
10
2
4
2020
7
2
8
2020
6
2
9
2020
3
Now for what I want, querying for each user with left outer join is quite simple with
select *
from last_12_months
left outer join rounds_count_by_users
on last_12_months.month = rounds_count_by_users.month
and last_12_months.year = rounds_count_by_users.year
and user_id = 1
Which gives me all the months even when the user has no played rounds. What I would like however is to be able to do this for every user and make a materialized view for easy querying. Is there a nice and easy way of doing this? To be clear this is the final table I want.
This query doesn't work at least, that much I know.
select *
from last_12_months
left outer join rounds_count_by_users
on last_12_months.month = rounds_count_by_users.month
and last_12_months.year = rounds_count_by_users.year
where user_id = 1
user_id
month
year
count_all
1
1
2020
15
1
2
2020
null
1
3
2020
12
1
4
2020
null
1
5
2020
10
1
6
2020
null
1
7
2020
null
1
8
2020
null
1
9
2020
null
1
10
2020
null
1
11
2020
null
1
12
2020
null
2
1
2020
null
2
2
2020
null
2
3
2020
null
2
4
2020
7
2
5
2020
null
2
6
2020
null
2
7
2020
null
2
8
2020
6
2
9
2020
3
2
10
2020
null
2
11
2020
null
2
12
2020
null
I made an SQL Fiddle for this (slightly different values but same schema)
PS: I know about table aliases and data modeling and that stuff. My question is strictly about how to achieve the final result.
This query:
select * from last_12_months
where (year = year(current_date) - 1 and month >= month(current_date))
or
(year = year(current_date) and month < month(current_date))
returns the rows of last_12_months for the last 12 months (not including the current month).
This query:
select distinct user_id from rounds_count_by_users
returns all the distinct user_ids (it would be better if these ids where stored in a users table).
You must CROSS join the above queries and then LEFT join rounds_count_by_users:
select u.user_id, m.month, m.year, r.count_all
from (
select * from last_12_months
where (year = year(current_date) - 1 and month >= month(current_date))
or
(year = year(current_date) and month < month(current_date))
) m cross join (select distinct user_id from rounds_count_by_users) u
left outer join rounds_count_by_users r
on m.month = r.month and m.year = r.year and u.user_id = r.user_id
order by u.user_id, m.month
See the demo.
So I managed it to do it this way after help in the comments.
This leaves me with exactly what I wanted.
with all_rows as (
select * from view_last_12_months inner join users on true
)
select id as user_id, all_rows.year, all_rows.month, count_all
from all_rows left outer join view_rounds_count_last_year last12
on last12.month = all_rows.month
and last12.year = all_rows.year
and all_rows.id = last12.user_id

SQL query group by with null values is returning duplicates

I have following query
My #dates table has following records:
month year saledate
9 2020 2020-09-01
10 2020 2020-10-01
11 2020 2020-11-01
with monthlysalesdata as(
select month(salesdate) as salemonth, year(salesdate) as saleyear,salesrepid, salespercentage
from salesrecords r
join #dates d on d.saledate = r.salesdate
group by salesrepid, salesdate),
averagefor3months as(
select 0 as salemonth, 0 as saleyear, salesrepid, salespercentage
from monthlysalesdata
group by salesrepid)
finallist as(
select * from monthlysalesdata
union
select * from averagefor3months
This query returns following records which gives duplicate for a averagefor3months result set when there is null record in the first monthlyresultdata. how to achieve average for 3 months as one record instead of having duplicates?
salesrepid salemonth saleyear percentage
232 0 0 null -------------this is the duplicate record
232 0 0 90
232 9 2020 80
232 10 2020 null
232 11 2020 100
My first cte has this result:
salerepid month year percentage
---------------------------------------------
232 9 2020 80
232 10 2020 null
232 11 2020 100
My second cte has this result:
salerepid month year percentage
---------------------------------------------
232 0 0 null
232 0 0 90
How to avoid the duplicate record in my second cte,
I suspect that you want a summary row per sales rep based on some aggregation. Your question is not clear on what is needed for the aggregation, but something like this:
with ym as (
select r.salesrepid, d.year, d.month, sum(<something>) as whatever
from salesrecords r join
#dates d
on d.saledate = r.salesdate
group by r.salesrepid, d.year, d.month
)
select ym.*
from ym
union all
select salesrepid, null, null, avg(whatever)
from hm
group by salesrepid;
I updated to selected the group by from the table directly instead of the previous cte and got my results. Thank you all for helping
with ym as (
select r.salesrepid, d.year, d.month, sum(<something>) as whatever
from salesrecords r join
#dates d
on d.saledate = r.salesdate
group by r.salesrepid, d.year, d.month
),
threemonthsaverage as(
select r.salesrepid, r.year, r.month, sum(something) as whatever
from salesrecords as r
group by salesrepid)
select ym *
union
select threemonthsaverage*

Outer join - oracle

I have 2 tabels
Current Ecpense table
-----------------------
Month-----Type-------spent
Feb 12 Shopping 100
Feb 12 Food 200
Jan 12 Shopping 456
Jan 12 Food 452
Jan 12 Fuel 120
Jan 12 Rent 900
Previous Expense
-----------------------
Type------ spent
Shopping 100
Food 100
Fuel 100
Rent 100
Now i want to join these two tables, the expected result is;
Month-----Type-------spent-----Previous Spent
Feb 12 Shopping 100 100
Feb 12 Food 200 100
Feb 12 Fuel 0 100
Feb 12 Rent 0 100
Jan 12 Shopping 456 100
Jan 12 Food 452 100
Jan 12 Fuel 120 100
Jan 12 Rent 900 100
Is there a way to do this?
Try:
select m.month,
p.type,
coalesce(c.spent,0) spent,
p.spent previous_spent
from (select distinct month from current_expense) m
cross join previous_expense p
left join current_expense c
on m.month = c.month and p.type = c.type
Common Oracle syntax
Select a.*, b.spent 'previous Sent'
from current_expense a, previous_expense b
where a.type = b.type
or the same thing in standard
Select a.*, b.spent 'previous Sent'
from current_expense as a
inner join previous_expense as b on a.type = b.type
I tend to write in SQL92 (more SQLness and less Oracle-ness)
Here is my answer:
select
z.month as month ,
z.type as type ,
nvl(c.spent,0) as spent ,
nvl(p.spent,0) as previous_spent
from
(select
x.month as month ,
y.type as type
from
(select distinct month
from current_expense) x
cross join
(select distinct type
from current_expense) y) z
left outer join current_expense c
on z.month = c.month and
z.type = z.type
left outer join previous_expense p
on z.type = p.type;