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 3 months ago.
Improve this question
If I run this query:
select date, sum(orders) as "Total orders"
from tbl
where date >=1 and date <= 4
group by date
How can I get the expected output as shown in the screenshot?
Use a left against generate_series():
select g.date,
sum(tbl.orders) as "Total orders"
from generate_series(1,4) as g(date)
left join tbl on tbl.date = g.date
group by g.date
WITH cte as (
SELECT date, orders
FROM dbo.Orders
),
cte2 as (
select top (SELECT MAX(date) FROM cte) ROW_NUMBER() over(order by a.name)
as date
from sys.all_objects a
)
SELECT cte2.date, SUM(ISNULL(orders, 0))
FROM cte2 LEFT JOIN cte ON cte2.date = cte.date
GROUP BY cte2.date
Related
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'
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
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
A table StatusHistory contains:
ID Status DtSince DtUntil
2415891 0 20200816 20200917
2415891 4 20200917 NULL
2415892 0 20200904 20200905
2415892 4 20200905 NULL
I need to select for each id the status for the beginning of each month and the end of it.
The user will input the date needed. For example:
User input --> #Month = '202009'
The select statement must return the status for dates 20200901 and 20201001
For records that are new and have dtSince>20200901 it should return the active row.For example for 2415892 it should return 4.
So the result set for #Month = 202009 should be :
Id BeginningOfMonth_status EndOfMonth_status
2415891 0 4
2415892 4 4
This is my solution
select * from
(
select * from
(
select *, ROW_NUMBER() over (partition by id order by dtSince desc) r from
dbo.StatusHistory
where DtUntil is null or (DtUntil <20201001and dtSince>=20200901) --2432290
)x
where x.r=1
)s1
inner join
(
select * from
(
select *, ROW_NUMBER() over (partition by id order by dtSince desc) r from
dbo.StatusHistory
where DtUntil is null or (DtUntil <20201001and dtSince>=20200901) --2432290
)x
where x.r=2
)s2
on s1.id = s2.id
Questions:
1)Is there anything less complex than my code?
2)with the above,i am not covering the For records that are new and have dtSince>20200901 requirement
Hmmm . . . You can get all the rows that cover a particular month using a where clause. Then use row_number() to enumerate the rows and conditional aggregation:
select id,
max(case when seqnum_asc = 1 then status end) as beginning_of_month,
max(case when seqnum_desc = 1 then status end) as end_of_month
from (select t.*,
row_nunber() over (partition by id order by dtsince) as seqnum_asc,
row_nunber() over (partition by id order by dtsince desc) as seqnum_desc
from t
where dtsince < dateadd(month, 1, convert(date, #Month + '01'))) and
(dtuntil >= convert(date, #Month + '01') or dtuntil is null)
) t
group by id
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.
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 7 years ago.
Improve this question
I have these rows in a table:
CarRentId LicensePalte UserId StartDate ReturnDate
1 29-456-15 1 2015-07-10 2015-07-15
50 29-456-15 2 2015-08-11 2015-08-15
When I query for date in where condition I want the result to be the last row and not the first one.
that is the query:
SELECT DISTINCT
ManufacturerName,
ModelName,
CreationYear,
Gear,
CurrentKM,
Picture,
DATEDIFF(D, '2015-08-12', '2015-08-15') * PricePerDay AS [Totalprice],
PricePerDay,
PricePerDayDelayed,
InventoryCars.LicensePlate,
CarsForRent.RentalReturnDate
FROM Models
JOIN Manufacturers
ON Models.ManufacturerID = Manufacturers.ManufacturerID
JOIN InventoryCars
ON InventoryCars.ModelID = Models.ModelID
JOIN CarsForRent
ON CarsForRent.LicensePlate = InventoryCars.LicensePlate
WHERE RentalReturnDate < '2015-08-12'
ORDER BY ManufacturerName, ModelName
Instead of getting 2015-08-15, the result I get is 2015-07-15 for the that specific LicensePlate number.
select distinct
ManufacturerName, ModelName, CreationYear,Gear, CurrentKM, Picture,
DATEDIFF(D, '2015-08-12', '2015-08-15')*PricePerDay as [Totalprice],PricePerDay,
PricePerDayDelayed, InventoryCars.LicensePlate,
(select max(RentalReturnDate) from CarsForRent where LicensePlate=InventoryCars.LicensePlate) as [RentalReturnDate]
from Models
join Manufacturers
on Models.ManufacturerID=Manufacturers.ManufacturerID
join InventoryCars
on InventoryCars.ModelID=Models.ModelID
join CarsForRent
on CarsForRent.LicensePlate=InventoryCars.LicensePlate
where RentalReturnDate<'2015-08-12'
order by ManufacturerName, ModelName
This is a lot of speculation, but regarding what I read from your question, I'm thinking that you might want the latest return date from your stack. If so, then you can do this:
SELECT DISTINCT
ManufacturerName,
ModelName,
CreationYear,
Gear,
CurrentKM,
Picture,
DATEDIFF(D, '2015-08-12', '2015-08-15') * PricePerDay AS [Totalprice],
PricePerDay,
PricePerDayDelayed,
InventoryCars.LicensePlate,
CarsForRent.RentalReturnDate
FROM Models
JOIN Manufacturers
ON Models.ManufacturerID = Manufacturers.ManufacturerID
JOIN InventoryCars
ON InventoryCars.ModelID = Models.ModelID
JOIN CarsForRent
ON CarsForRent.LicensePlate = InventoryCars.LicensePlate
WHERE RentalReturnDate < '2015-08-12'
ORDER BY CarsForRent.RentalReturnDate, ManufacturerName, ModelName
This code basically will check the latest return date, if they have the same return date, it will order by manufacturer name, and if by chance both are the same, it will order by model name.