SQL making last year's data into another column [closed] - sql

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I have a data set that looks like:
revenue country date
100 US 3/13/2014
200 US 3/14/2014
300 CA 3/13/2014
150 US 3/13/2013
200 CA 3/13/2013
How can I run a query to get last year's revenue in the same date into another column?
revenue country data revenue_last_year
100 US 3/13/2014 150
200 US 3/14/2014 0 or null
300 CA 3/13/2013 200
Thanks in advance!

For last year's revenue on the given date:
select revenue, country, date
, (
select revenue
from revenue r2
where r1.country=r2.country
and r1.date = dateadd(yy,1,r2.date)
) as LastYearRevenue
from revenue r1
Check on SQLFiddle.

Essentialy, you join two queries on the same data set. Let's say you your table is called CountryRevenue.
SELECT
A.revenue, A.country, A.date, B.revenue as revenue_last_year
FROM
(SELECT * FROM CountryRevenue where YEAR(date) = 2014) AS A
INNER JOIN
(SELECT * FROM Country Revenue WHERE YEAR(date) = 2013) AS B
ON
A.country = B.country
Something like this should do what you want.

Related

How to aggregate event dates based on aggregated table? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 16 days ago.
Improve this question
I have a table that aggregates disables/reenables events in the following format:
Disabled Date
Enabled Date
Count
01/01
01/01
5
01/01
02/01
2
03/01
05/01
1
04/01
05/01
5
and want to build a report that aggregates the number of disables and reenables per day:
Date
Enables
Disables
01/01
5
7
02/01
2
0
03/01
0
1
04/01
0
5
05/01
6
0
I was able to build the following query that works for days that have at least one disable and one enable:
SELECT
disables.disable_date AS disable_date,
disables.disable_count disable_count,
enables.enable_count enable_count
FROM
(SELECT
disable_date,
sum(disable_count) disable_count
FROM table
GROUP BY 1) AS disables,
(SELECT
enable_date,
sum(disable_count) enable_count
FROM table
GROUP BY 1) AS enables
WHERE enables.enable_date = disables.disable_date;
Any suggestions how to build the complete output? I'm not sure this is the right strategy, so a JOIN could also be considered.
Thanks!
;WITH cte
AS (SELECT disabled_date AS Date,
Sum(count) AS Disables
FROM table1
GROUP BY disabled_date
UNION ALL
SELECT enabled_date AS Date,
Sum(-count) AS Disables
FROM table1
GROUP BY enabled_date)
SELECT cte.date,
COALESCE(Sum(CASE
WHEN cte.disables > 0 THEN cte.disables
END), 0) AS Enables,
COALESCE(Sum(CASE
WHEN cte.disables < 0 THEN -cte.disables
END), 0) AS Disables
FROM cte
GROUP BY cte.date
ORDER BY cte.date;
TEST
http://sqlfiddle.com/#!18/13cace/3

arithmetic operation on alias of column of table [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last month.
Improve this question
I have written a query which fetch the data like this and I wanted to calculate the opening and maindata I have formula for then which is ( CurrentEmp + Empjoined - EmpLeft ) as opening and ((EmpLeft*100)/((CurrentEmp+opening)/2)) as maindata respectively I have written it in query but I gets the error saying invalid column name .
month year CurrentEmp join leftemp
January 2021 10 2 1
February 2021 15 3 2
March 2021 20 5 2
and the output that I expect is
month year CurrentEmp join leftemp opening
January 2021 10 2 1 11
February 2021 15 3 2 16
March 2021 20 5 2 23
I have written the below code
with t0(n) as ( select n from ( values (1),(2),(3),(4),(5),(6),(7),(8),(9),(10)) t(n)),ns as(select row_number()
over(order by t1.n) - 1 n from t0 t1, t0 t2, t0 t3),calendar as (
select top(12) DATEADD(month, n, '2021-01-01' ) dt , DATEADD(month, n , '2021-01-31')dd from ns order by n) select cast(DATENAME(month, dt) as nvarchar(max)) AS month,cast(DATENAME(YEAR, dt) as nvarchar(max))AS Year,
(SELECT COUNT(*) FROM EmployeeDetail e left join Separation s on e.Id = s.EmployeeId
WHERE (e.CompanyId=1 and e.DateOfJoining <calendar.dt and e.EmpStatus = 1) or(s.CompanyId = 1 and e.DateOfJoining <calendar.dt and s.LastWorkingDate >= calendar.dt)) AS CurrentEmp,
(select count(*) from EmployeeDetail where DateOfJoining >=calendar.dt And DateOfJoining<=calendar.dd and CompanyId = 1) as Empjoined,
(select count(*) from Separation where LastWorkingDate >= calendar.dt and LastWorkingDate < =calendar.dd and CompanyId =1) as EmpLeft,
(CurrentEmp+Empjoined-EmpLeft) as opening , cast (((EmpLeft*100)/((CurrentEmp+opening)/2)) as decimal(10,2)) as maindata
from calendar order by dt
An alias in the current select statement cannot be used as a variable within that same select statement.
You'll need to either:
Repeat the calculation:
(CurrentEmp+Empjoined-EmpLeft) as opening,
-- NOTE: opening IS REPLACED BY SAME CALC: (CurrentEmp+Empjoined-EmpLeft)
cast (((EmpLeft*100) /
((CurrentEmp+(CurrentEmp+Empjoined-EmpLeft))/2))
as decimal(10,2)) as maindata
Or, move the primary calculation of opening to a sub-query and join on that.
But, given the simplicity and low overhead of the calculation, I'd just repeat the calculation.

Create View with date in one table [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 months ago.
Improve this question
I have a table data as below 'table 1', would like to create a view as below 'view1' with the table 1, was that possible?
Table 1
Code
Outletname
Date
Total
A
Outlet A
01/09/2022
10
A
Outlet A
02/09/2022
20
B
Outlet B
01/09/2022
30
B
Outlet B
02/09/2022
40
View 1
Date
Outlet A Total
Outlet B Total
01/09/2022
10
30
02/09/2022
20
40
WITH totals AS
( -- get the total info by outlet and date
SELECT outletname, date, sum(total) as total
FROM table1
GROUP BY outletname, date
), dates AS
( -- get list of all the dates
SELECT date
FROM table1
GROUP BY date
) -- use left joins to get the results
SELECT dates.date, ja.total as [outlet a total], jb.total as [outlet b total]
FROM dates
LEFT JOIN totals ja on dates.date = j1.date and outletname = 'Outlet A'
LEFT JOIN totals jb on dates.date = j1.date and outletname = 'Outlet B'

bring many years (oracle plsql) [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
hi this query bring for "one year 2020" ; but, i want to bring this query.
state_name ,2020 total deaths ,2021 total deaths
One option might be
select
s.statename,
sum(case when extract(year from st.date_) = 2020 then st.death end) deaths_2020,
sum(case when extract(year from st.date_) = 2021 then st.death end) deaths_2021
from statecases1 st join state_ s on s.statecode = st.statecode
group by s.statename
order by s.statename;
Your query can't return data for 2020 and 2021 because of the WHERE clause you used (you restricted dates to year 2020).
You can use this. Although i am not 100% clear but this is what i thought you need - sum by state and year. You can also use pivot.
WITH yearly_data AS
(SELECT s.statename, to_char(st.date_, 'YYYY') AS YEAR, sum(death) death
FROM covid.statecases1 st
JOIN covid_state_ s ON s.statecode=st.statecode
GROUP BY s.statename, to_char(st.date_, 'YYYY'))
SELECT DISTINCT a.statename, b.death 2020_death,c.death 2021_death
FROM yearly_data a
LEFT JOIN yearly_data b ON a.statename=b.statename AND b.year='2020'
LEFT JOIN yearly_data c ON a.statename=c.statename AND c.year='2021'
ORDER BY 1

How to group by quarters(1 year = 4 quarters) in SQL? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
Question Description:Show for each customer and product combination, the average sales quantities for 4 quarters,Q1, Q2, Q3 and Q4(in four separate columns) –Q1 being the first 3 months of the year (Jan, Feb & Mar), Q2 the next 3 months (Apr, May & Jun), and so on–ignore the YEAR component of the dates (i.e., 3/11/2001is considered the same date as 3/11/2002, etc.).Also compute the average for the “whole” year(again ignoring the YEAR component, meaning simply compute AVG) along with the total quantities(SUM) and the counts(COUNT).
table as follow:enter image description here
The sample result:enter image description here
I am a beginner on SQL and I met such a problem. It needs to group the 4 quarters just by using aggregate functions and group by clause.
with cte as (
select
customer,
product,
case
when (month < 4) then 'Q1'
when (month >= 4 AND month < 7) then 'Q2'
when (month >= 7 AND month < 10) then 'Q3'
when (month >= 10) then 'Q4'
end AS quarter,
quant
from bgg.table_sof
),
cte_full as (
select
customer,
product,
avg(quant) as average,
sum(quant) as total,
count(quant) as count
from bgg.table_sof
GROUP BY customer, product
)
select
cte_full.customer,
cte_full.product,
avg(cte1.quant) as Q1_AVG,
avg(cte2.quant) as Q2_AVG,
avg(cte3.quant) as Q3_AVG,
avg(cte4.quant) as Q4_AVG,
average,
total,
count
from cte_full
left join cte cte1 on cte_full.customer = cte1.customer and cte_full.product = cte1.product
left join cte cte2 on cte_full.customer = cte2.customer and cte_full.product = cte2.product
left join cte cte3 on cte_full.customer = cte3.customer and cte_full.product = cte3.product
left join cte cte4 on cte_full.customer = cte4.customer and cte_full.product = cte4.product
where cte1.quarter = 'Q1' OR cte2.quarter = 'Q2' OR cte3.quarter = 'Q3' OR cte4.quarter = 'Q4'
group by cte_full.customer, cte_full.product, average, total, count;
It's a tricky task for a beginner. My advice is to start with some theory and easy practice.
There is two CTE (common table expression):
the first is for defining quarters from months.
the second (cte_full) for calculating the last 3 columns in the result table.
And final select joins separately calculated avg by quarters to result.
I'm sure it isn't easy for understanding for beginner, feel free to ask.