How do I create a new column showing difference between maximum date in table and date in row? - sql

I need two columns: 1 showing 'date' and the other showing 'maximum date in table - date in row'.
I kept getting a zero in the 'datediff' column, and thought a nested select would work.
SELECT date, DATEDIFF(max_date, date) AS datediff
(SELECT MAX(date) AS max_date
FROM mytable)
FROM mytable
GROUP BY date
Currently getting this error from the above code : mismatched input '(' expecting {, ';'}(line 2, pos 2)
Correct format in the end would be:
date | datediff
--------------------------
2021-08-28 | 0
2021-07-26 | 28
2021-07-23 | 31
2021-08-11 | 17

If you want the date difference, you can use:
SELECT date, DATEDIFF(MAX(date) OVER (), date) AS datediff
FROM mytable
GROUP BY date

You can do this using the analytic function MAX() Over()
SELECT date, MAX(date) OVER() - date FROM mytable;
Tried this here on sqlfiddle

Related

Grouping by two parameters in SQL Server

I have a table with this structure:
id | timestamp | barcode
The timestamp is datetime and the barcode is a full barcode, from which I need only the first 9 digits.
I need to get the count for each product for each day with one query.
So I basically need a result like:
date | item number | count
-----------+-------------+--------
12.02.2019 | 827384950 | 32
Item number is left(barcode, 9).
You can try below - using cast() to convert timestamp to date and then add that in group by
select cast([timestamp] as date),left(barcode, 9) as itemnumber,count(*)
from tablename
group by cast([timestamp] as date),left(barcode, 9)
this query has better performance
select date, itemnumber, count(*) from
(select cast([timestamp] as date) as date,left(barcode, 9) as itemnumber
from tablename) a
group by date,itemnumber

Sub-query is Not Working for Date_Part()

I want to pass the subquery as an argument to the EXTRACT() function of Postgres to get the number of the day of the week but it is not working.
Working Code:
SELECT EXTRACT(dow FROM DATE '2018-06-07');
It returns:
+-------------+
| date_part |
|-------------|
| 4.0 |
+-------------+
Not Working Code:
SELECT EXTRACT(DOW FROM DATE
(SELECT start_date from leaves where submitted_by=245 and type_id = 16)
);
It returns
syntax error at or near "SELECT"
LINE 1: SELECT EXTRACT(DAY FROM DATE (SELECT submitted_on FROM leave...
I don't know why EXTRACT() function is not accepting subquery result as the query:
SELECT start_date from leaves where submitted_by=245 and type_id = 16;
returns the following which I think is identical I have passed as a
date string in the working example.
+--------------+
| start_date |
|--------------|
| 2018-06-07 |
+--------------+
Can somebody correct it or let me know some other way to get the number of the day of the week.
Just apply it to the column of the select:
SELECT EXTRACT(DOW from start_date)
from leaves
where submitted_by=245 and type_id = 16
If you really want to use a scalar sub-query, then you must get rid of the DATE keyword, that is only needed to specify date constants.
SELECT EXTRACT(DOW FROM
(SELECT start_date from leaves where submitted_by=245 and type_id = 16)
);
Put the function inside the select:
select (select extract(dow from start_date)
from leaves
where submitted_by = 245 and type_id = 16
)
I don't see the advantage for using a subquery in the select for this (as opposed to -- say -- moving the subquery to the from. But this should do what you want.

Hive + Pass previous day date to like clause

Am trying to fetch records from hive table based on the previous date.
Example: If table is as follows
CustomerVisit table
ID NAME VISIT_DATE
------------------
01 Harish 2018-02-31
03 Satish 2017-02-13
04 Shiva 2018-03-04
Now i need to fetch all records that have visit_date = 2018-03-04 (i.e today's date -1).
Expected Query something like:
select ID, Name from CustomerVisit where
visit_date like concat((select date_sub(current_date, 1)),'%')
I have tried following
select current_date; - Gives current date
select date_sub(current_date, 1) - Gives previous date
select concat(tab1.date1,'%') from
(select date_sub(current_date, 1) as date1) as tab1; -- Gives the previous date appended with % which i need to use in like
but when i use the above as sub-query like below it fails with
select tab2.id, (select concat(tab1.date1,'%') as pattern from
(select date_sub(current_date, 1) as date1) as tab1) from CustomerVisit as tab2 limit 1;
FAILED: ParseException line 1:0 cannot recognize input near 'seelct' 'current_date' ''
How to write query to get results for previous date?
You don't need a LIKE clause. Just select using an equal to (=)
select ID, Name from CustomerVisit where
visit_date = date_sub(current_date, 1);

Select count for each specific date

I have the following need:
I need to count the number of times each id activated from all dates.
Let's say the table looks like this:
tbl_activates
PersonId int,
ActivatedDate datetime
The result set should look something like this:
counted_activation | ActivatedDate
5 | 2009-04-30
7 | 2009-04-29
5 | 2009-04-28
7 | 2009-04-27
... and so on
Anyone know how to do this the best possible way? The date comes in the following format '2011-09-06 15:47:52.110', I need to relate only to the date without the time. (summary for each date)
you can use count(distinct .. )
and if the ActivatedDate is datetime you can get the date part
select Cast(ActivatedDate AS date), count(distinct id)
from my_table
group by ast(ActivatedDate AS date)
You can use to_char function to remove the time from date
select count(*) counted_activation,
to_char(activatedDate,"yyyy-mm-dd") ActDate
from table1
group by to_char(activatedDate,"yyyy-mm-dd");
Use 'GROUP BY' and 'COUNT'. Use CONVERT method to convert datetime to Date only
SELECT CONVERT(DATE,activatedate), COUNT(userId)
FROM [table]
GROUP BY CONVERT(DATE,InvoiceDate)

How can I get Quarter to Date in Hive SQL?

I'm having a hard time getting the quarter to date values from Hive SQL.
How can I get the first day of the current quarter in Hive sql?
Table name: Orders
Fields: date, order_num, sales_num
Please advise.
This seems to be the cleanest way
with t as (select date '2016-08-27' as dt)
select add_months(trunc(dt,'MM'),-(month(dt)-1)%3) from t
;
2016-07-01
Here are 2 more options
with t as (select date '2016-08-27' as dt)
select trunc(add_months(dt,-(month(dt)-1)%3),'MM')
from t
;
2016-07-01
with t as (select date '2016-08-27' as dt)
select add_months(trunc(dt,'YY'),cast((month(dt)-1) div 3 * 3 as INT))
from t
;
2016-07-01
For earlier versions
with t as (select '2016-08-27' as dt)
select printf('%04d-%02d-%02d',year(dt),(((month(dt)-1) div 3) * 3) + 1,1)
from t
2016-07-01
Same, but for today
with t as (select from_unixtime(unix_timestamp(),'yyyy-MM-dd') as today)
select printf('%04d-%02d-%02d',year(today),(((month(today)-1) div 3) * 3) + 1,1) as
from t
2017-04-01
If you can't use the various date function that Dudu suggested, you can always cast it to string, parse out the month, and use a case statement. Depending on your version of Hive, you may have to use a simple case instead of searched.
(assuming YYYY-MM-DD)
case cast (substring (cast(<date field> as varchar(10)),6,2) as integer)
when between 1 and 3 then 1
when between 4 and 6 then 2
when between 7 and 9 then 3
else 4
end
Ugly, but it should work.