Current Year Sales and Previous Year Sales in the same table? - datetime

Good Morning,
I am looking to add 'Previous Year Sales' to the same week into a Teradata pull, but I am failing on the coding. The Baseline I would code to get the sales of that week/year would be:
SELECT a."WEEK_NBR" AS "YearWeek"
, SUM(a."Sales") AS "CurrentYearSales"
FROM "SALESTABLE" AS a
Which would result in:
YearWeek CurrentYearSales
201901 $7,499
201902 $2,300
201903 $6,360
...
202001 $4,500
202002 $9,000
202003 $8,500
I want to be able to have the Prior year's sales same week on the same line, if the prior year is there in the data table. That way the finished table would look like:
YearWeek CurrentYearSales PriorYearSales
201901 $7,499 NULL
201902 $2,300 NULL
201903 $6,360 NULL
...
202001 $4,500 $7,499
202002 $9,000 $2,300
202003 $8,500 $6,360
When I search, all I can find is how to do this with the current week's data, but is this possible with all records in the table?

Edit: As you SUMmed the data you need to aggregate before the join.
You need a self join, assuming WEEK_NBR is numeric:
with cte as
(
SELECT a."WEEK_NBR" AS "YearWeek"
, SUM(a."Sales") AS "CurrentYearSales"
FROM "SALESTABLE" AS a
group by 1
)
select ...
from cte as t1
left join cte as t2
on t2.YearWeek = t1.Ye arWeek- 100
As #Andrew noted, this will also work for a string because Teradata will do an automatic typecast to a float when you add a number to a string or compare numeric and string (I would prefer writing an explicit type cast though)

Related

SQLite how to select row based on a column max

I have the following table
UserID, Cost, date
1. 23. 2015-04-02
2. 17. 2015-03-14
1. 63. 2015-09-23
2. 49. 2013-03-17
2. 12. 2013-04-23
1. 96. 2016-01-01
What I want is a list of USERID & date with the largest cost
So
Userid 1 cost 96 date 2016-01-01
Userid 2 cost 49 date 2013-03-17
I have tried
select date, userid, max(cost) from table group by userid
But I'm confused with will the date always be from the correct row
Thanks
In SQLite 3.7.11 or later, values from other columns are guaranteed to come from a row that matches the max().
Consider a generalized approach for most RDMS versions. Below uses a derived table subquery:
SELECT t2.UserID, t2.MaxOfCost, t1.Date
FROM Table t1
INNER JOIN
(SELECT UserID, Max(Cost) As MaxOfCost,
FROM Table) t2
ON t1.UserID = t2.UserID
AND t1.Cost = t2.MaxOfCost

sqlite query comparing data in different rows

i have the following table where i have the date( not a primary key) and rating ('A' being the highest grade):
date rating
03-10-2010 C
03-09-2010 C
03-08-2010 B
03-07-2010 B
03-06-2010 B
03-05-2010 B
03-04-2010 A
I need to make a query where i compare the rating in order to return the result for each 'date'.
For example. considering the date 03-10-2010, i want to know when the last rating downgrade happened. if the downgrade was 1 day ago return '1' as result, if it was 2 days ago return '2' and if was older than 3 days return 0.
And i would do the same query for each date, getting an array with the results.
i'm stuck trying to do this and i have no more ideas how to do it. Anyone can help me please?
thanks.
You want the difference, in days, between the date of each record and the date of the record before the last downgrade.
When you have a specific record, the record before the last downgrade is the record that
has a higher rating than this record, and
has a lower date than this record, and
is the latest record of those.
In SQL, this can be done with a correlated subquery:
SELECT date,
rating,
(SELECT date
FROM MyTable AS downgrade
WHERE downgrade.date < MyTable.date
AND downgrade.rating < MyTable.rating
ORDER BY date DESC
LIMIT 1) AS downgrade_date
FROM MyTable
date rating downgrade_date
---------- ---------- ----------
2010-03-04 A
2010-03-05 B 2010-03-04
2010-03-06 B 2010-03-04
2010-03-07 B 2010-03-04
2010-03-08 B 2010-03-04
2010-03-09 C 2010-03-08
2010-03-10 C 2010-03-08
To compute the difference, convert the date into a numeric value.
You can then use this value for further computations:
SELECT date,
rating,
CASE
WHEN days <= 3 THEN days
ELSE 0
END AS whatever
FROM (SELECT date,
rating,
julianday(date) -
julianday((SELECT date
FROM MyTable AS downgrade
WHERE downgrade.date < MyTable.date
AND downgrade.rating < MyTable.rating
ORDER BY date DESC
LIMIT 1)) AS days
FROM MyTable)

SQLite: How do I find the daily/weekly/monthly/yearly average of a row count

I've just started learning SQLite, and had a question.
Here is an example of what I mean.
This is my CSV:
date
2010-10-24
2010-10-31
2010-11-01
2011-02-14
2011-02-15
2011-02-16
2011-10-01
2012-01-15
2012-05-12
2012-05-14
2012-08-12
2012-08-26
My code:
SELECT STRFTIME('%Y-%m', date) AS 'month', COUNT() AS 'month_count'
FROM tableName
GROUP BY STRFTIME('%Y-%m', date);
The result (in comma-delimited form):
month, month_count
2010-10, 2
2010-11, 1
2011-02, 3
2011-10, 1
2012-01, 1
2012-05, 2
2012-08, 2
What I'm looking for now, is a way to get the average number of 'month_count' per month, which is of course different from just the average of 'month_count'. That is, the former equals 0.55, while the latter equals 1.71, and I'm trying ti calculate the former.
I tried using AVG(COUNT()), though that obviously made no logical sense.
I'm guessing I'd have to store the code-generated table as a temporary file, then get the average from it, though I'm not sure how to properly write it.
Does anyone know what I'm missing?
Try the code below:
create table test(date date);
insert into test values ('2010-10-24');
insert into test values ('2010-10-31');
insert into test values ('2010-11-01');
insert into test values ('2011-02-14');
insert into test values ('2011-02-15');
insert into test values ('2011-02-16');
insert into test values ('2011-10-01');
insert into test values ('2012-01-15');
insert into test values ('2012-05-12');
insert into test values ('2012-05-14');
insert into test values ('2012-08-12');
insert into test values ('2012-08-26');
SELECT a.tot_months
, b.month_diff
, cast(a.tot_months as float) / b.month_diff avg_count
FROM (SELECT COUNT(*) tot_months FROM test) a
, (SELECT cast((strftime('%m',max(date))+12*strftime('%Y',max(date))) as int) -
cast((strftime('%m',min(date))+12*strftime('%Y',min(date))) as int) as 'month_diff'
FROM test) b
;
Output:
C:\scripts>sqlite3 < foo.sql
12|22|0.545454545454545

Query if a customer ID has a previous order in the last week: How To?

I am using SQLite 3.7.4 and have a table that includes:
TABLE: 'Orders'
ID OrderDate
1234 2011-06-01 00:00:00
1245 2011-06-04 00:00:00
1234 2011-06-05 00:00:00
I'd like to be able to select the 'OrderDate' & 'ID' where, for a given OrderDate there is a previous order in the last 1 week.
So, for the data above:
The first record ID 1234 has an order
on 2011-06-01 00:00:00, but has none
previous - so isn't selected.
The next record ID 1245 has an order
on 2011-06-04 00:00:00 but none in
week prior to 2011-06-04, so not
selected.
The 3rd record ID 1234 order made on
2011-06-05 00:00:00 has a previous
order on 2011-06-01, so this record
is selected.
I have just about managed to get my head around using strftime('%s',OrderDate) for date differences,but can't work out how to query by taking the yyyy-mm-dd part of the OrderDate record and looking back '-7 days' to see if there are 1 or more records within that range ?
Any guideance appreciated :)
Not certain I understand, but this gives the output you're looking for, given the sample data.
sqlite> select o1.id, o1.orderdate from orders o1
...> inner join orders o2 on (o1.id = o2.id
...> and o2.orderdate >= date(o1.orderdate, '-7 day')
...> and o2.orderdate < o1.orderdate);
1234|2011-06-05
You should probably look at SQLite Date and Time Functions.

Getting All the record of particular month - Building SQL Query

I need some help to build SQL Query. I have table having data like:
ID Date Name
1 1/1/2009 a
2 1/2/2009 b
3 1/3/2009 c
I need to get result something like...
1 1/1/2009 a
2 1/2/2009 b
3 1/3/2009 c
4 1/4/2009 Null
5 1/5/2009 Null
6 1/6/2009 Null
7 1/7/2009 Null
8 1/8/2009 Null
............................
............................
............................
30 1/30/2009 Null
31 1/31/2009 Null
I want query something like..
Select * from tbl **where month(Date)=1 AND year(Date)=2010**
Above is not completed query.
I need to get all the record of particular month, even if some date missing..
I guess there must be equi Join in the query, I am trying to build this query using Equi join
Thanks
BIG EDIT
Now understand the OPs question.
Use a common table expression and a left join to get this effect.
DECLARE #FirstDay DATETIME;
-- Set start time
SELECT #FirstDay = '2009-01-01';
WITH Days AS
(
SELECT #FirstDay as CalendarDay
UNION ALL
SELECT DATEADD(d, 1, CalendarDay) as CalendarDay
FROM Days
WHERE DATEADD(d, 1, CalendarDay) < DATEADD(m, 1, #FirstDay)
)
SELECT DATEPART(d,d.CalendarDay), **t.date should be (d.CalendarDay)**, t.Name FROM Days d
LEFT JOIN tbl t
ON
d.CalendarDay = t.Date
ORDER BY
d.CalendarDay;
Left this original answer at bottom
You need DATEPART, sir.
SELECT * FROM tbl WHERE DATEPART(m,Date) = 1
If you want to choose month and year, then you can use DATEPART twice or go for a range.
SELECT * FROM tbl WHERE DATEPART(m,Date) = 1 AND DATEPART(yyyy,Date) = 2009
Range :-
SELECT * FROM tbl WHERE Date >= '2009-01-01' AND Date < '2009-02-01'
See this link for more info on DATEPART.
http://msdn.microsoft.com/en-us/library/ms174420.aspx
You can use less or equal to.
Like so:
select * from tbl where date > '2009-01-01' and date < '2009-02-01'
However, it is unclear if you want month 1 from all years?
You can check more examples and functions on "Date and Time Functions" from MSDN
Create a temporary table containing all days of that certain month,
Do left outer join between that table and your data table on tempTable.month = #month.
now you have a big table with all days of the desired month and all the records matching the proper dates + empty records for those dates who have no data.
i hope that's what you want.

Resources