Add year to column before compare in SQL query - sql

I am querying a MySQL database and I need to add a year to a column (of type date) before the compare operation.
I would expect is to look something like this:
SELECT count(*) AS count
FROM users
WHERE renewed + 1 year < '2009-12-12'

Use:
SELECT COUNT(*) AS count
FROM USERS u
WHERE DATE_ADD(u.renewed, INTERVAL 1 YEAR) < '2009-12-12'
Reference:
DATE_ADD

You can use the mysql DATE_ADD function:
DATE_ADD(renewed, INTERVAL 1 YEAR)

Related

sql query to find specific entries based on date range

I have a database with a table containing the history of the login times of all accounts. The table includes columns USERID and LOGIN_DATE. I want to find those users who have not logged in for over 60 days, so an SQL query that says
Find users who have a login date which was greater than 60 days ago, but have no entry for any date more recently than 60 days ago
Can anyone suggest how I would do this ?
Following can be a solution
select USERID, min(login_date) mind, max(login_date) maxd
from Logins
group by UserId
having max(login_date) < dateadd(d,-60,getdate())
You could use aggregation, and filter on users whose maximum login date is older than 60 days:
select userid
from mytable
group by userid
having max(login_date) < current_date - interval '60' day
You did not tell which database you are using, so this uses standard date arithmetics. You might need to adapt that to your actual database (all major databases have alternatives for this).
Now the question was tagged Oracle. The above would work; you might want to truncate the time portion of the date to check on entire days. And if you want to display the last login, just add the aggregate function to the select clause:
select userid, max(login_date) last_login_date
from mytable
group by userid
having max(login_date) < trunc(current_date) - interval '60' day
You can use aggregation:
select userid
from t
group by userid
having max(logindate) < trunc(sysdate) - interval '60' day;
Date/time functions are notoriously database-specific, so the exact syntax for the having clause might depend on your database.

How to create a view in PostgreSQL with where clause

I am trying to create a view in Postgres
I have 3-4 time stamps in each closing_date where I need to select only the latest time stamp of each day
And also I have to restrict the closing_date to only 30 days (shown in SQL query below)
Below is the query from SQL data which I had created
CREATE VIEW dbo.CashBreaks_30Days_View as
SELECT Closing_date,Bo,Desk,Breaks_Staus,Owner,status,Team,
SLA,Age_Bucket_EntryDate,Age_Bucket_ValueDate,Age_EntryDate,Age_ValueDate,
[Type_(2)]
FROM Master_Data_CashBreaks
WHERE Closing_date >= cast(getdate()-37 as date);
If I understood you correctly, something like this might return result you want:
create or replace view cash_breaks_30days_view
as
select a.list_of_columns
from master_data_cashbreaks a
where a.closing_date >= trunc(sysdate) - 30 --> the last 30 days
and a.closing_date = (select max(b.closing_date) --> subquery is used to return
from master_data_cashbreaks b -- the last timestamp per date
where b.id = a.id
and trunc(b.closing_date) = trunc(a.closing_date)
)
There are few mistakes in your code:
[Type_(2)] - Not a valid SQL
getdate() - There is no such function available in Oracle. you should use the trunc(SYSDATE) instead.
getdate()-37 - Why -37, when you want the last 30 days data. It should be 30.
Your query should look like this in oracle:
CREATE VIEW dbo.CashBreaks_30Days_View as
SELECT * FROM
(SELECT Closing_date,Bo,Desk,Breaks_Staus,Owner,status,Team,
SLA,Age_Bucket_EntryDate,Age_Bucket_ValueDate,Age_EntryDate,Age_ValueDate,
ROW_NUMBER() OVER (PARTITION BY Closing_date ORDER BY Closing_date DESC) AS RN
FROM Master_Data_CashBreaks
WHERE Closing_date >= TRUNC(SYSDATE) - 30)
WHERE RN = 1;
Your SQL contains a lot of errors
square brackets are invalid in SQL identifiers, if you have such a column you need to use double quotes. It's unclear to me if your column is named "[Type_(2)]" or maybe just `"Type_(2)"
There is no getdate() in SQL or in Postgres. Use current_date instead
So fixing all those error, your statement should look like this:
CREATE VIEW dbo.CashBreaks_30Days_View
as
SELECT Closing_date, Bo, Desk, Breaks_Staus, Owner, status,
Team, SLA, Age_Bucket_EntryDate,
Age_Bucket_ValueDate, Age_EntryDate, Age_ValueDate,
"[Type_(2)]" -- or maybe only "Type_(2)"
FROM Master_Data_CashBreaks
WHERE Closing_date >= current_cate - 30;
i am able to create with the below
create or replace view cashbreaks_30days_view_latesttime
as
select a. Column details
from master_data a
where a. Closing_date >= NOW() - interval '40 days'
and a.closing_date = (select max(b.closing_date)
from master_data b
where date(b.closing_date) = date(a.closing_date));

sum last n days quantity using sql window function

I am trying to create following logic in Alteryx and data is coming from Exasol database.
Column “Sum_Qty_28_days“ should sum up the values of “Qty ” column for same article which falls under last 28 days.
My sample data looks like:
and I want following output:
E.g. “Sum_Qty_28_days” value for “article” = ‘A’ and date = ‘’2019-10-8” is 8 because it is summing up the “Qty” values associated with dates (coming within previous 28 days) Which are:
2019-09-15
2019-10-05
2019-10-08
for “article” = ‘A’.
Is this possible using SQL window function?
I tried myself with following code:
SUM("Qty") OVER (PARTITION BY "article", date_trunc('month',"Date")
ORDER BY "Date")
But, it is far from what I need. It is summing up the Qty for dates falling in same month. However, I need to sum of Qty for last 28 days.
Thanks in advance.
Yes, this is possible using standard SQL and in many databases. However, this will not work in all databases:
select t.*,
sum(qty) over (partition by article
order by date
range between interval '27 day' preceding and current row
) as sum_qty_28_days
from t;
If your RDBMS does not support the range frame, an alternative solution is to use an inline subquery:
select
t.*,
(
select sum(t1.qty)
from mytable t1
where
t1.article = t.article
and t1.date between t.date - interval 28 days and t.date
) sum_qty_28_days
from mytable t

Selecting by month in PostgreSQL

I want to select rows according to the month of a date or timestamp column like this:
SELECT id, name, birthday
FROM employee.person
WHERE Month(birthday) > 10;
But I only get error messages in PostgreSQL.
How can this be done?
You can use EXTRACT function, like this:
SELECT id, name, birthday FROM employee.person
WHERE EXTRACT(MONTH FROM birthday) > 10;
Your problem comes from the fact that there is no such thing as Month function in PostgreSQL. Check online documentation here to see what you can get instead. Extract should be enough.
If you want you can also extract the month name using the following function.
SELECT TO_CHAR(DATE(REPORT_DATE), 'Month') FROM TABLE_NAME

Help me build a SQL select statement

SQL isn't my greatest strength and I need some help building a select statement.
Basically, this is my requirement. The table stores a list of names and a timestamp of when the name was entered in the table. Names may be entered multiple times during a week, but only once a day.
I want the select query to return names that were entered anytime in the past 7 days, but not today.
To get a list of names entered today, this is the statement I have:
Select * from table where Date(timestamp) = Date(now())
And to get a list of names entered in the past 7 days, not including today:
Select * from table where (Date(now())- Date(timestamp) < 7) and (date(timestamp) != date(now()))
If the first query returns a set or results, say A, and the second query returns B, how can I get
B-A
Try this if you're working with SQL Server:
SELECT * FROM Table
WHERE Timestamp BETWEEN
dateadd(day,datediff(day,0,getdate()),-7),
AND dateadd(day,datediff(day,0,getdate()),0)
This ensures that the timestamp is between 00:00 7 days ago, and 00:00 today. Today's entries with time greater than 00:00 will not be included.
In plain English, you want records from your second query where the name is not in your first query. In SQL:
Select *
from table
where (Date(now())- Date(timestamp) < 7)
and (date(timestamp) != date(now()))
and name not in (Select name
from table
where Date(timestamp) = Date(now())
)
not in
like
select pk from B where PK not in A
or you can do something like
Select * from table where (Date(now())- Date(timestamp) < 7) and (Date(now())- Date(timestamp) > 1)