Syntax to get sum(sales) group by brand but different date - sql

My data is like so
item date country sales
----------------------------------------
motorola 2015-01-01 US 10
motorola 2015-01-01 UK 20
motorola 2015-01-02 US 40
motorola 2015-01-02 UK 80
motorola 2015-01-03 US 120
motorola 2015-01-03 UK 150
motorola 2015-01-04 US 170
motorola 2015-01-04 US 180
I want to get the daily sales delta of motorola from 2 jan 2015 until 4 jan 2015.
So for example
total sales for 1 jan 2015 is 10 (US) + 20(UK) = 30
total sales for 2 jan 2015 is 120 so daily sales delta (sales on date minus D-1) is 90
total sales for 3 jan 2015 is 270 so daily delta is 150
total sales for 4 jan 2015 is 350 so daily delta is 80
I'm expecting the result tuple :
date dailyDelta
2015-01-02 90
2015-01-03 150
2015-01-04 80
What is the syntax to get this? I'm using SQL Server 2012.
Thanks

This is it, the query logic is as simple as it gets, the performance better than inner joins:
select date, sum(sales) - coalesce(lag(sum(sales), 1) over (order by date), 0)
from my_sales
group by date
order by date
Use window function lag. Play with it: http://sqlfiddle.com/#!6/bebab/8 and read about it: https://msdn.microsoft.com/en-us/library/hh231256.aspx
briefly, lag(sum(sales), 1) over (order by date) means "get sum(sales) column of previous record of this query, ordered by date", coalesce(XXX, 0) means "when XXX is null, let's pretend it was a zero"

I don't really see much of a way around a self join. Here is how it would work:
select a.date
, a.item
, sum(a.sales) - sum(b.sales) as DailyDelta
from table a
join table b on a.product = b.product
and b.date = dateadd(day, -1, a.date)
group by a.date
, a.item
Not great performance wise but it will get the job done.

The following query is based on MySQL, but you can tweak it to make it work for SQL server. I hope SQL Server will also support the same
select o.date, t.tsales - sum(sales) delta from test o, (select date, sum(sales) tsales from test group by date) t
where o.date = t.date -1 group by o.date
For the above query I got the following result
"date" "delta"
"2015-01-01" "90"
"2015-01-02" "150"
"2015-01-03" "80"

use a self join
declare #t table (item varchar(10), [date] date,country char(2), sales int)
insert into #t (item, [date],country, sales) values
('motorola','2015-01-01','US',10),
('motorola','2015-01-01','UK',20),
('motorola','2015-01-02','US',40),
('motorola','2015-01-02','UK',80),
('motorola','2015-01-03','US',120),
('motorola','2015-01-03','UK',150),
('motorola','2015-01-04','US',170),
('motorola','2015-01-04','US',180)
;with a as (select row_number() over (order by [date]) r,[date],sum(sales) n from #t group by [date])
select a.[date],a.n-isnull(a1.n,0) dailyDelta from a join a a1 on a.r =a1.r+1

Try this..
SELECT date,
( sum(sales) - LAG(sum(sales),1,0) over (order by sales) ) as dailyDelta
FROM Table
group by date
order by date;

Related

Query two unbalanced tables

Sum across two tables returns unwanted Sum from one table multiplied by the number of rows in the other
I have 1 table with Actual results recorded by date and the other tables contains planned results recorded by month.
Table 1(Actual)
Date Location Amount
01/01/2019 Loc1 1000
01/02/2019 Loc1 700
01/01/2019 Loc2 7500
01/02/2019 Loc2 1000
02/01/2019 Loc1 500
Table 2(Plan)
Year Month Location Amount
2019 1 Loc1 1500
2019 1 Loc2 8000
2019 2 Loc1 800
I have tried various differed Joins using YEAR(Table1.date) and Month(table1.date) and grouping by
Month(Table1.Date) but I keep running into the same problem where the PlanAmount is multiplied by however many rows in the Actual table...
in the example of loc1 for Month 1 below I get
Year Month Location PlanAmount ActualAmount
2019 1 Loc1 3000 1700
I would like to return the below
Year Month Location PlanAmount ActualAmount
2019 1 Loc1 1500 1700
2019 1 Loc2 8000 8500
2019 2 Loc1 800 500
Thanks in advance for any help
D
You can do this with a full join or union all/group by:
select yyyy, mm, location,
sum(actual_amount) as actual_amount,
sum(plan_amount) as plan_amount
from ((select year(date) as yyyy, month(date) as mm, location,
amount as actual_amount, 0 as plan_amount
from actual
group by year(date) as yyyy, month(date) as mm, location
) union all
(select year, month, location,
0 as actual_amount, amount as plan_amount
from actual
group by year, month, location
)
) ap
group by yyyy, mm, location;
This ensures that you have rows, even when there are no matches in the other table.
To get the required results you need to group the first table on year of date, month of date and location and need to select the columns year, month, location and sum of amount from group after that you need to join that resultant r
SELECT
plans.year,
plans.month,
plans.location,
plans.plan_amount,
grouped_results.actual_amount
FROM plans
INNER JOIN (
SELECT
datepart(year, date) AS year,
datepart(month, date) AS month,
location,
SUM(amount) AS actual_amount
FROM actuals
GROUP BY datepart(year, date), datepart(month, date), location
) as grouped_results
ON
grouped_results.year = plans.year AND
grouped_results.month = plans.month AND
grouped_results.location = plans.location
I think the problem is that you are using sum(PlanTable.Amount) when grouping. Try using max(PlanTable.Amount) instead.
select
p.Year,
p.Month,
p.Location,
sum(a.Amount) as actual_amount,
max(p.Amount) as plan_amount
from
[Plan] p left join Actual a
on year(a.date) = p.year
and month(a.date) = p.Month
and a.Location = p.Location
group by
p.year,
p.month,
p.Location
SQL Fiddle
get year and month from date and use them in join , most dbms has year and month functions you can use according to your DBMS
select year(t1.date) yr,month(t1.date) as monthofyr ,t1.Location,
sum(t1.amount) as actual_amoun,
sum(t2.amount) as planamount
from table1 t1 left join table2 t2 on
month(t1.date)= t2.Month and t1.Location=t2.Location
and year(t1.date)=t2.year
group by year(t1.date) ,month(t1.date),Location

Return next value in Sybase based on condition

I have a table like this:
date ticker price
01/01/17 APPL 700
01/01/17 SNAP 15
01/02/17 APPL 750
01/02/17 SNAP 13
I'd want to retrieve the next price for that ticker as an additional column, like so:
date ticker price next_price
01/01/17 APPL 700 750
01/01/17 SNAP 15 13
01/02/17 APPL 750 NULL
01/02/17 SNAP 13 NULL
I think in most databases you'd be able to do something like this:
SELECT date, ticker, price, RANK() OVER (PARTITION BY ticker
ORDER BY date ASC) AS RANK
from table_name
and then do something with the rank to find the next_price. Unfortunately Sybase ASE is sadly limited and doesn't support RANK().
Any ideas on what to use instead?
Assumptions:
each unique ticker value has a max of 1 record for any given date
next_price is for the next day where 'next' could be defined as +1 day, +2 days, +1 week, +1 month, etc
Off the top of my head ... a bit of a convoluted correlated sub-query to find next_price ...
Setup table and data:
create table mytab
([date] date
,ticker varchar(10)
,price int
)
go
insert mytab values ('1/1/2017','APPL',700)
insert mytab values ('1/1/2017','SNAP',15)
insert mytab values ('1/2/2017','APPL',750)
insert mytab values ('1/2/2017','SNAP',13)
insert mytab values ('1/5/2017','APPL',800)
insert mytab values ('1/7/2017','SNAP',23)
go
One possible query:
select t1.[date],
t1.ticker,
t1.price,
(select price
from mytab t2
where t2.ticker = t1.ticker
and t2.[date] = (-- find the 'next' available day for t1.ticker
select min([date])
from mytab t3
where t3.ticker = t1.ticker
and t3.[date] > t1.[date]
)
) as next_price
from mytab t1
order by 1,2
go
date ticker price next_price
---------------- ---------- ----------- -----------
Jan 1 2017 APPL 700 750
Jan 1 2017 SNAP 15 13
Jan 2 2017 APPL 750 800
Jan 2 2017 SNAP 13 23
Jan 5 2017 APPL 800 NULL
Jan 7 2017 SNAP 23 NULL
Tested on ASE 15.7 SP138
You would not use rank() for this. You would use lead().
You can use a correlated subquery:
select t.*,
(select top 1 t2.price
from table_name t2
where t2.ticker = t.ticker and t2.date > t.date
order by t2.date asc
) as next_price
from table_name t;
If you know the date is the next calendar date, then you could use a left join instead -- that would be more efficient.

Adding each row with aprevious row in sql query

Lets say I have a table with a values below:
Date sales
===== =====
Jan 100
Feb 150
Mar 500
and so on
How can I query this table with the results below:
Date Sales Total
==== ===== ======
Jan 100 100
Feb 150 250 (Jan + Feb)
Mar 500 750 (Jan + Feb + mar)
I know it can be done in SP looping through but is there a simple query?
your help is appreciated.
Thanks,
J
A windowed SUM should work on several DBMS. A SQL Server example is below (please let us know which one you are using otherwise):
DECLARE #T TABLE ([Date] DATE, [Sales] INT)
INSERT #T VALUES ('1/1/2015', 100), ('2/1/2015', 150), ('3/1/2015', 500)
SELECT
[Date],
[Sales],
SUM([Sales]) OVER (ORDER BY [Date]) AS [Total]
FROM #T
ORDER BY
[Date]
This generates the following output:
Date Sales Total
---------- ----------- -----------
2015-01-01 100 100
2015-02-01 150 250
2015-03-01 500 750
Since SQL Server 2008 doesn't support the ORDER BY in a windowed aggregate (only since 2012), here's a method to do same thing. It's very inefficient - there's just not a very efficient way to do this otherwise I've seen unfortunately.
;WITH CTE AS (
SELECT
ROW_NUMBER() OVER (ORDER BY [Date]) AS RowId,
[Date],
[Sales]
FROM #T
)
SELECT
A.[Date],
A.[Sales],
SUM(B.[Sales]) AS [Total]
FROM CTE A
INNER JOIN CTE B
ON B.RowId <= A.RowId
GROUP BY
A.[Date],
A.[Sales]
ORDER BY
A.[Date]

SQL spread month value into weeks

I have a table where I have values by month and I want to spread these values by week, taking into account that weeks that spread into two month need to take part of the value of each of the month and weight on the number of days that correspond to each month.
For example I have the table with a different price of steel by month
Product Month Price
------------------------------------
Steel 1/Jan/2014 100
Steel 1/Feb/2014 200
Steel 1/Mar/2014 300
I need to convert it into weeks as follows
Product Week Price
-------------------------------------------
Steel 06-Jan-14 100
Steel 13-Jan-14 100
Steel 20-Jan-14 100
Steel 27-Jan-14 128.57
Steel 03-Feb-14 200
Steel 10-Feb-14 200
Steel 17-Feb-14 200
As you see above, the week that overlaps between Jan and Feb needs to be calculated as follows
(100*5/7)+(200*2/7)
This takes into account tha the week of the 27th has 5 days that fall into Jan and 2 into Feb.
Is there any possible way to create a query in SQL that would achieve this?
I tried the following
First attempt:
select
WD.week,
PM.PRICE,
DATEADD(m,1,PM.Month),
SUM(PM.PRICE/7) * COUNT(*)
from
( select '2014-1-1' as Month, 100 as PRICE
union
select '2014-2-1' as Month, 200 as PRICE
)PM
join
( select '2014-1-20' as week
union
select '2014-1-27' as week
union
select '2014-2-3' as week
)WD
ON WD.week>=PM.Month
AND WD.week < DATEADD(m,1,PM.Month)
group by
WD.week,PM.PRICE, DATEADD(m,1,PM.Month)
This gives me the following
week PRICE
2014-1-20 100 2014-02-01 00:00:00.000 14
2014-1-27 100 2014-02-01 00:00:00.000 14
2014-2-3 200 2014-03-01 00:00:00.000 28
I tried also the following
;with x as (
select price,
datepart(week,dateadd(day, n.n-2, t1.month)) wk,
dateadd(day, n.n-1, t1.month) dt
from
(select '2014-1-1' as Month, 100 as PRICE
union
select '2014-2-1' as Month, 200 as PRICE) t1
cross apply (
select datediff(day, t.month, dateadd(month, 1, t.month)) nd
from
(select '2014-1-1' as Month, 100 as PRICE
union
select '2014-2-1' as Month, 200 as PRICE)
t
where t1.month = t.month) ndm
inner join
(SELECT (a.Number * 256) + b.Number AS N FROM
(SELECT number FROM master..spt_values WHERE type = 'P' AND number <= 255) a (Number),
(SELECT number FROM master..spt_values WHERE type = 'P' AND number <= 255) b (Number)) n --numbers
on n.n <= ndm.nd
)
select min(dt) as week, cast(sum(price)/count(*) as decimal(9,2)) as price
from x
group by wk
having count(*) = 7
order by wk
This gimes me the following
week price
2014-01-07 00:00:00.000 100.00
2014-01-14 00:00:00.000 100.00
2014-01-21 00:00:00.000 100.00
2014-02-04 00:00:00.000 200.00
2014-02-11 00:00:00.000 200.00
2014-02-18 00:00:00.000 200.00
Thanks
If you have a calendar table it's a simple join:
SELECT
product,
calendar_date - (day_of_week-1) AS week,
SUM(price/7) * COUNT(*)
FROM prices AS p
JOIN calendar AS c
ON c.calendar_date >= month
AND c.calendar_date < DATEADD(m,1,month)
GROUP BY product,
calendar_date - (day_of_week-1)
This could be further simplified to join only to mondays and then do some more date arithmetic in a CASE to get 7 or less days.
Edit:
Your last query returned jan 31st two times, you need to remove the =from on n.n < ndm.nd. And as you seem to work with ISO weeks you better change the DATEPART to avoid problems with different DATEFIRST settings.
Based on your last query I created a fiddle.
;with x as (
select price,
datepart(isowk,dateadd(day, n.n, t1.month)) wk,
dateadd(day, n.n-1, t1.month) dt
from
(select '2014-1-1' as Month, 100.00 as PRICE
union
select '2014-2-1' as Month, 200.00 as PRICE) t1
cross apply (
select datediff(day, t.month, dateadd(month, 1, t.month)) nd
from
(select '2014-1-1' as Month, 100.00 as PRICE
union
select '2014-2-1' as Month, 200.00 as PRICE)
t
where t1.month = t.month) ndm
inner join
(SELECT (a.Number * 256) + b.Number AS N FROM
(SELECT number FROM master..spt_values WHERE type = 'P' AND number <= 255) a (Number),
(SELECT number FROM master..spt_values WHERE type = 'P' AND number <= 255) b (Number)) n --numbers
on n.n < ndm.nd
) select min(dt) as week, cast(sum(price)/count(*) as decimal(9,2)) as price
from x
group by wk
having count(*) = 7
order by wk
Of course the dates might be from multiple years, so you need to GROUP BY by the year, too.
Actually, you need to spred it over days, and then get the averages by week. To get the days we'll use the Numbers table.
;with x as (
select product, price,
datepart(week,dateadd(day, n.n-2, t1.month)) wk,
dateadd(day, n.n-1, t1.month) dt
from #t t1
cross apply (
select datediff(day, t.month, dateadd(month, 1, t.month)) nd
from #t t
where t1.month = t.month and t1.product = t.product) ndm
inner join numbers n on n.n <= ndm.nd
)
select product, min(dt) as week, cast(sum(price)/count(*) as decimal(9,2)) as price
from x
group by product, wk
having count(*) = 7
order by product, wk
The result of datepart(week,dateadd(day, n.n-2, t1.month)) expression depends on SET DATEFIRST so you might need to adjust accordingly.

SQL Sum by week from daily table

I have a table with sales for products.
The sales are per day. like
product date sales
1 '2013-11-01' 100
1 '2013-11-02' 423
1 '2013-11-03' 700
1 '2013-11-04' 233
2 '2013-11-01' 623
2 '2013-11-02' 451
2 '2013-11-03' 9000
I want to get a query which will show me the week over week sum of sales
So something like:
product week ending sales
1 '2013-11-01' 10000
1 '2013-11-08' 15000
2 '2013-11-01' 4900
2 '2013-11-08' 30000
I'm not sure how I get this weekly groups when summing up.
I'm using teradata
If you are using Teradata 14 you can leverage the DayNumber_Of_Week() function in the database TD_SYSFNLIB:
SELECT s.Product
, s.Date + (7-DayNumber_Of_Week(s.date)) AS WeekEndingDate /* Saturday */
, SUM(s.Sales) AS Sales
FROM sales AS S
GROUP BY 1,2;
This should work in Teradata 13.10 as well.
Using Sys_Calendar:
SELECT s.Product
, s.DATE + (7-c.Day_Of_Week) AS WeekEndingDate /* Saturday */
, SUM(s.Sales) AS Sales
FROM sales AS S
INNER JOIN
Sys_Calendar.Calendar c
ON S.date = c.calendar_date
GROUP BY 1,2;
I know very little about TERADATA, but I believe you can leverage the sys_calendar.calendar table, something like:
SELECT s.Product, c.week_of_year, SUM(s.sales) AS Sales
FROM sales AS s
JOIN sys_calendar.calendar as C
ON s.date = c.date
You'd need the Year in there as well, so as to not group up week 1 of 2013 with week 1 of 2012.