Sum of everything up to a date [duplicate] - sql

This question already has answers here:
Calculate running total / running balance
(6 answers)
Closed 3 months ago.
I have a table with two columns, date and number of pieces, just like this:
pieces Date
100 2022-01-01
200 2022-02-01
300 2022-03-01
and so on.
I want to sum the number of pieces in the way that I increment the newest month, something like this:
january - 100 pieces
february - 300 pieces
march - 600 pieces
How would I do that?
What I've tried so far is make individual selects with one sum up to a point and then union with another, up to another point, but it seems counter productive.
select
sum(pieces)
, 'january' as month
from
table
where
date <= '2022-01-31'
union
select
sum(pieces)
, 'february' as month
from
table
where
date <= '2022-02-28'
union
select
sum(pieces)
, 'march' as month
from
table
where
date <= '2022-03-31'

say your dataframe is 'df'
step 1: create new column as "month" by 'month<-months(as.Date("Date"))" #new column will be created
step 2: use "group by" or "cumsum"

Related

Date format in sas concatenate with a proc sql under conditions

i have a macro_variable :%let date=201909
and table :
ID Sending-date item
1 15-jul-2019 A
2 23-sep-2019 B
3 12-sep-2019 A
4 1-jan-2019 B
5 5-feb-2019 B
What i'm wondering to do is to verify if there is an item sent in the month indicated in my date (09 september) and the two previous months (august and july) using a proc sql and without adding new variables.
the result_table expected is like this :
Month Year Number of items
9 2019 2
8 2019 0
7 2019 1
The biggest problem is how to convert the format of the date in the table like my macro_variable date.
Here's one method.
I used cutoff_date instead of date, because it helps differentiate the dates more easily.
Use INTNX() to do date calculations. In this case, I set the cutoff to be the end of cutoff_month and the start of two months prior. You may need to define that a bit more clearly to meet your needs but this works.
%let cutoff_date=201909;
proc sql;
create table want as
select month(sending_date) as Month, count(*) as num
from have
where sending_date between intnx('month', input("&cutoff_date.", yymmn6.), 0, 'e') and intnx('month', input("&cutoff_date.", yymmn6.), -2, 'b')
group by calculated Month;
quit;

Data of last 6 quarter including current quarter

How to get data of last 6 quarter in Oracle including current quarter. I mean if I run the query today so data between 01-JAN-2018 to 30-JUN-2019 should come in the query.
You could do something like this:
SELECT
*
FROM
DUAL
WHERE
DATE_FIELD >= (SYSDATE - (30*(3*6)))
What this query is doing is taking the current date (SYSDATE), and grabbing all values from the previous 6 quarters. The rationale is:
30 = days in a month | 3 = months in a quarter | 6 = quarters specified by OP
You can use add_months and trunc functions for date value with Q(quarter) argument
select t.*
from tab t
where insert_date between
trunc(add_months(sysdate,-3*5),'Q')
and trunc(add_months(sysdate,3),'Q')-1;
Demo for verification
for the starting date, -3*(6-1) = -3*5 considered, starting from 5 quarter back to be able to count 6 quarter including the current quarter. 3 is
obvious as being the number of months in each quarter.

I'm trying to calculate variance using sql between two same days of two years

I will try to be simple as possible to make my question crystal-clear. I have a table that's called 'fb_ads' (it's about different facebook compaigns for different stores in USA) on BigQuery, it contains the following columns:
STORE : name of store
CLICKS: number of clicks.
IMPRESSIONS: number of impressions of the ad
COST: the ad cost
DATE: AAAA-MM-DD
Frequency: number of visitors of a store
So, I'm trying to calculate the variance between two years 2017 and 2018.
Here is the variance I'm trying to calculate:
Variance_Of_Frequency = ((Frequency in 2018 at date X) - ((Frequency in 2017 at date X))/((Frequency in 2017 at date X)
The problem is, that I'll have to compare the same day of the week close to Date X;
For example, if I have a compaign run on a Monday 2017-08-13, I'll need to compare to another monday in 2018 close to 2018-08-13 (it might be a monday on 2018-08-15 for example).
This is a daily variance!
I tried to make a weekly variance calculating and I don't know if it's correct, here is how I did it:
I first started with aggregating my daily table to a weekly tables using the following query:
creating my weekly_table
SELECT
year_week,
STORE,
min(DATE ) as DATE ,
SUM(IMPRESSIONS ) AS FB_IMPRESSIONS ,
SUM(CLICKS ) AS FB_CLICKS ,
SUM(COST) AS FB_COST ,
SUM(Frequency) AS FREQUENCY,
FROM (
SELECT
*,
CONCAT(cast(ANNEE as string), LPAD(cast((extract(WEEK from date)) as string), 2, '0') ) AS year_week
FROM `fb_ads`)
GROUP BY
year_week,
STORE,
ORDER BY year_week
Then I tried to calculate the variance using this:
SELECT
base.*, (base.frequency-lw.frequency) / lw.frequency as VAR_FF
FROM
`weekly_table` base
JOIN (
SELECT
* EXCEPT (date),
DATE_ADD(DATE(TIMESTAMP(date)) , INTERVAL 1 Week)AS date
FROM
`weekly_table` ) lw
ON
base.date = lw.date
AND base.store= lw.store
Anyone has any idea how to do the daily thing or if my weekly queries are correct ?
Thanks!
For a given date, you want to know the date of the nearest Monday to the same date in the following year...
SET #dt = '2017-08-17';
SELECT CASE WHEN WEEKDAY(#dt + INTERVAL 1 YEAR) > 3
THEN ADDDATE(ADDDATE(#dt + INTERVAL 1 YEAR,INTERVAL 1 WEEK),INTERVAL - WEEKDAY(#dt + INTERVAL 1 YEAR) DAY)
ELSE ADDDATE(#dt + INTERVAL 1 YEAR,INTERVAL - WEEKDAY(#dt + INTERVAL 1 YEAR) DAY)
END x;
Obviously, I could remove all those + INTERVAL 1 YEAR bits by defining #dt that way to begin with.

Select next value where it equals another value

I have a table of the fiscal year for 100 years. i.e.
I am wanting to do add a column which shows the fiscal year that each week_ending_date belongs to. So in the table above week number 1, and week_ending_date 2013-10-05 would belong to fiscal year ending 2014.
In short I simply want each value in the added column to be the year part of week_ending_date where the next week_number is 52.
Here would be the pseudo code of what I am trying to achieve.
SELECT
Week_Ending_Date,
(SELECT NEXT VALUE FOR Week_Ending_Date (***but as only year***) FROM Fiscal_Calendar WHERE FC.Week_Number = 52)
FROM Fiscal_Calendar AS FC
JOIN Shipped_Container AS SC
ON SC.Fiscal_Week_Ending = FC.Week_Ending_Date
Bare in mind this has 100 years in the table and so I can't select the last value and makes using WHERE difficult (for me).
One way you can do this is by subtracting 7 * week number, taking the year and adding 1:
select 1 + year(dateadd(day, -7 * week_number, week_ending_date))

convert month name in varchar to date so as to order by month [duplicate]

This question already has answers here:
Convert month name to month number in SQL Server
(14 answers)
Closed 9 years ago.
A table exists which stores month name in the form of string..
I want to order by year and month so as to get proper result.
year(string) Month(string) data
------------ ------------ ----
2012 August bigbox
2012 December samllbox
2013 April samll box
2012 September larg
I want to order by year and month. as in 2012,2013...
Jan,feb,march....
I am aware of the method of
case statement when
Month = 'january' THEN 1
Month - FEB THEN 2
But i do'nt want to use this as the procedure will be too big..
Your best option is to use the proper date type. Otherwise, create a table (inline or physical) to map your string months.
SELECT 1 AS month, 'January' AS strMonth
UNION ALL
SELECT 2, 'February'
UNION ALL
SELECT 3, 'March'
...
SELECT 12, 'December'
Then map this your table. See a demo
SELECT *
FROM TABLE
ORDER BY [year] DESC,
DATEPART(month,[Month] + ' 01 ' + CONVERT(VARCHAR(4),[YEAR]))
The above code will give you what you want , but i would strongly suggest you reconsider your design.
Right now you are reserving a string type field which would be at least 15 characters long. This field does not have any value than for display reasons. You could have a DATETIME field that would be much easier to short by (not having to do calculations there) and if you would like to display the name of the month you could use:
DATENAME ( month, DateField )