I am trying to write a sql query to which will give me result or select row from a table if the datediff is equal to 7 days or 24 days.
MY table look something like this:
TableA:
ID ExpirationDate
I want to select row if ExpirationDate-DateTime.NOW == 7 days or 24 days.
Thanks
SELECT *
FROM
TableA
WHERE
DATEDIFF(DAY, ExpirationDate, GETDATE()) = 7
OR DATEDIFF(DAY, ExpirationDate, GETDATE()) = 24
SELECT ID
FROM TableA
WHERE DATEDIFF(DAY, ExpirationDate, NOW()) IN (7, 24)
If you are using SQL Server the syntax DateDiff(day, ExpirationDate, GetDate()) IN (7,24) will do the job. For mysql you can use DateDiff(ExpirationDate, CurDate()) IN (7, 24). the clause IN (7, 24) is equivalent to = 7 Or = 24 etc.
Related
RDBMS: MySQL
The time column(s) datatype is of datetime
For every hour of the 24 hour day I need to retrieve the number of rows in which their start_time matches the hour OR the end_time is great than or equal to the hour.
Below is the current query I have which returns the data I need but only based off of one hour. I can loop through and do 24 separate queries for each hour of the day but I would love to have this in one query.
SELECT COUNT(*) as total_online
FROM broadcasts
WHERE DATE(start_time) = '2018-01-01' AND (HOUR(start_time) = '0' OR
HOUR(end_time) >= '0')
Is there a better way of querying the data I need? Perhaps by using group by somehow? Thank you.
Not exactly sure if i am following, but try something like this:
select datepart(hh, getdate()) , count(*)
from broadcasts
where datepart(hh, starttime) <=datepart(hh, endtime)
and cast(starttime as date)=cast(getdate() as date) and cast(endtime as date)=cast(getdate() as date)
group by datepart(hh, getdate())
Join with a subquery that returns all the hour numbers:
SELECT h.hour_num, COUNT(*) AS total_online
FROM (SELECT 0 AS hour_num UNION SELECT 1 UNION SELECT 2 ... UNION SELECT 23) AS h
JOIN broadcasts AS b ON HOUR(b.start_time) = h.hour_num OR HOUR(b.end_time) >= h.hour_num
WHERE DATE(b.start_time) = '2018-01-01'
GROUP BY h.hour_num
I have a table with some dates. I need a query which will return the max (last) date from this table and last date of quarter this max date belongs to.
So for data i table
ID| EDATE
--+----------
1|2014-03-06
2|2014-10-12
this query should return 2014-10-12 and 2014-12-31.
As I understand you want the last day of the quarter, so 31 March, 30 June, 30 Sept, 31 Dec? So you can use the answer from Gordon Linoff and adjust it to do that.
You only need a case statement on month(date) and concat that with the year.
http://dev.mysql.com/doc/refman/5.1/de/control-flow-functions.html
str_to_date(
concat(
year(edate),
(case
when month(edate) in (1, 2, 3) then '-03-31'
when month(edate) in (4, 5, 6) then '-06-30'
when month(edate) in (7, 8, 9) then '-09-30'
else '-12-31'
end)
),
'%Y-%m-%d'
)
Getting the day of the last quarter for the date is a bit yucky, but possible. Here is a sort of brute force solution:
select edate,
str_to_date(concat(year(edate), '-', 1 + floor((month(edate) - 1)/ 3)) * 3, '-',
(case when month(edate) in (1, 2, 3, 10, 11, 12) then 31 else 30 end)),
'%Y-%m-%d'
)
from table t
order by edate desc
limit 1;
Here is a SQL Fiddle that demonstrates it.
You can use LAST_DAY to select the last day of a specific month depending on where your quarters end you may have to change the 3,6,9,12 to different months.
select t1.max_date,
(
case
when month(max_date) <= 3
then last_day(concat(year(max_date),'-3-1'))
when month(max_date) <= 6
then last_day(concat(year(max_date),'-6-1'))
when month(max_date) <= 9
then last_day(concat(year(max_date),'-9-1'))
else last_day(concat(year(max_date),'-12-1'))
end
) last_quarter_day
from (
select max(EDATE) max_date from myTable
) t1
I found the simplest answer:
SELECT MAKEDATE(YEAR(edate),1)
+ INTERVAL QUARTER(edate) QUARTER
- INTERVAL 1 DAY
This query takes the first day of year, adds quarters to it and subtracts 1 day to get the last day in wanted quarter. So the required query should look like:
SELECT MAX(edate),
MAKEDATE(YEAR(MAX(edate)),1)
+ INTERVAL QUARTER(MAX(edate)) QUARTER
- INTERVAL 1 DAY
FROM table
How to select week data (more precisely, last 7 days data) from the current date in the fastest way as I have millions or rows in the table. I have a time stamp of created_date in sql table.
I have tried this
SELECT Created_Date
FROM Table_Name
WHERE Created_Date >= DATEADD(day,-7, GETDATE())
I have two question:
Is this query is correct?
Is this is the fastest way to get the last seven day data from a table having millions of rows ?
Yes, the syntax is accurate and it should be fine.
Here is the SQL Fiddle Demo I created for your particular case
create table sample2
(
id int primary key,
created_date date,
data varchar(10)
)
insert into sample2 values (1,'2012-01-01','testing');
And here is how to select the data
SELECT Created_Date
FROM sample2
WHERE Created_Date >= DATEADD(day,-11117, GETDATE())
to select records for the last 7 days
SELECT * FROM [TableName]
WHERE Created_Date >= DATEADD(day, -7, GETDATE())
to select records for the current week
SET DATEFIRST 1 -- Define beginning of week as Monday
SELECT * FROM [TableName]
WHERE CreatedDate >= DATEADD(day, 1 - DATEPART(WEEKDAY, GETDATE()), CONVERT(DATE, GETDATE()))
AND CreatedDate < DATEADD(day, 8 - DATEPART(WEEKDAY, GETDATE()), CONVERT(DATE, GETDATE()))
if you want to select records for last week instead of the last 7 days
SET DATEFIRST 1 -- Define beginning of week as Monday
SELECT * FROM [TableName]
WHERE CreatedDate >= DATEADD(day, -(DATEPART(WEEKDAY, GETDATE()) + 6), CONVERT(DATE, GETDATE()))
AND CreatedDate < DATEADD(day, 1 - DATEPART(WEEKDAY, GETDATE()), CONVERT(DATE, GETDATE()))
The query is correct
2A. As far as last seven days have much less rows than whole table an index can help
2B. If you are interested only in Created_Date you can try using some group by and count, it should help with the result set size
I have a table that contains only Month and Year field both as int.
Given an input say month, 6 months.
I need to project the data that are 6 months old.
for example I have data from 2001 , 1st Janaury till date. Given input as 6 months , so I have to go back 6 months
from cuurent date to get the result .
Output will be Data From Jan 2001 to Jan 2012.
I have done the program using the right,substring, string comparison.(a nasty hack)
Is there any prominent way of doing so?
DDL
Declare #t table (Mnth int, Yr int)
Insert Into #t
-- 2011
Select 1,2011 Union All select 2,2011 Union All Select 3, 2011 Union ALL Select 4,2011 Union ALL
Select 5,2011 Union All select 6,2011 Union All Select 7, 2011 Union ALL Select 8,2011 Union ALL
Select 9,2011 Union All select 10,2011 Union All Select 11, 2011 Union ALL Select 12,2011 Union ALL
--2012
Select 1,2012 Union All select 2,2012 Union All Select 3, 2012 Union ALL Select 4,2012 Union ALL
Select 5,2012 Union All select 6,2012 Union All Select 7, 2012 Union ALL Select 8,2012 Union ALL
Select 9,2012 Union All select 10,2012 Union All Select 11, 2012 Union ALL Select 12,2012
Declare #inputMonth int = 6
I am trying without string conversion
Select Mnth,Yr,YEAR(DATEADD(mm,-#inputMonth,getdate())),MONTH(DATEADD(mm,-#inputMonth,getdate()))
From #t
WHERE YEAR(DATEADD(mm,-#inputMonth,getdate())) < Yr
AND MONTH(DATEADD(mm,-#inputMonth,getdate())) < Mnth
But it is not working
Thanks
You could always convert to datetime and compare that.
Something like:
WHERE
CONVERT(Datetime,
CONVERT(nvarchar(4), YearPart) + '-' + CONVERT(nvarchar(2), MonthPart) + '-01')
) > DATEADD(month, -6, GETUTCDATE())
i.e. concatenate your two columns to yield CONVERT(Datetime, "2011-1-01"), for instance.
As this answer to another question points out, ify ou don't want to do string conversions, you would have to add to do a series of DATEADD to 0, which is 1900-01-01.
WHERE
DATEADD(month, MonthPart-1, DATEADD(year, YearPart-1900, 0))
> DATEADD(month, -6, GETUTCDATE())
Without casting.
Select *
From your table
Where (yr= #someYear and mt between #someMonth-6 and #someMonth) or
(#someMonth <6 and yr =#someYear - 1 and mt >= 12-(6-#someMonth) )
try this..
DECLARE #CurrentMonth tinyint,#CurrentYear tinyint
SELECT #currentMonth=Datepart(mm,getdate())
SELECT #CurrentYear=Datepart(yy,getdate())
IF((#currentmonth-6)<0)
begin
SELECT month,year FROM #t WHERE year =(#CurrentYear-1) AND month >(#currentMonth+6)
UNION ALL
SELECT month,year FROM #t WHERE year=#CurrentYear AND month <= #CurrentMonth
end
ELSE
begin
SELECT month,year from #t WHERE year=#CurrentYear AND month between #CurrentMonth-6
AND #CurrentMonth+1
end
Realized I hadn't thought it through, new solution:
declare #m int
set #m = 11
declare #startDate datetime
set #startDate = dateadd(mm,-#m,getdate())
select yr,mnth
from t
where
DateAdd(day, 1,
DateAdd(month, mnth - 1,
DateAdd(Year,yr-1900, 0))) >#startDate
and
DateAdd(day, 1,
DateAdd(month, mnth - 1,
DateAdd(Year,yr-1900, 0))) < getDate()
Table A, columns OrderId, OrderTimeStamp (datetime).
I want to SELECT all records for any date, but between 10 am and 1 pm, for example.
How do I do that?
Thanks!
declare #t table(d datetime)
insert #t values('2012-01-01 09:00'),('2012-01-01 10:00'),('2012-01-01 11:00')
select cast(d as time) from #t where cast(d as time) between '10:00' and '13:00'
In T-SQL DatePart will do the trick:
To get all records from 10:00 - 12:59:
SELECT *
FROM TableA
WHERE DATEPART(hh, [OrderTimeStamp]) >= 10 AND DATEPART(hh, [OrderTimeStamp]) < 13
Or if you want to get all records from 10:00 - 13:00 (seconds/milliseconds are omitted):
SELECT *
FROM TableA
WHERE DATEPART(hh, [OrderTimeStamp]) >= 10 AND DATEPART(hh, [OrderTimeStamp]) < 13
OR (DATEPART(hh, [OrderTimeStamp]) = 13 AND DATEPART(mi, [OrderTimeStamp]) = 0)
Keep in mind that 24h values are returned from the DatePart function when used with hh as a format.
For further info see here:
http://msdn.microsoft.com/en-us/library/ms174420.aspx
UPDATE
Since ouy are working with SQL 2008, you can make use of the TIMEdata type and make your query much simpler (and correct as well):
SELECT *
FROM TableA
WHERE CONVERT(TIME(7), [OrderTimeStamp ]) >= '10:00:00.0000000'
AND CONVERT(TIME(7), [OrderTimeStamp ]) <= '13:00:00.0000000'
For futher info see here:
http://msdn.microsoft.com/en-us/library/bb677243.aspx
select *
from tableA
where datepart(hh, OrderTimeStamp) between 10 and 13
if you need to filter by minutes (like 13:20 and 14:15), try the suggestions on this link
select *
from TableA
where datepart(hh, OrderTimeStamp) >= 10 and datepart(hh, OrderTimeStamp) < 13
update:
doh, ntziolis beat me by 30 seconds. one thing to note, if you want 1pm included, be sure to make the last part of the where <=. if you want to only go up to 12:59.999 pm < is appropriate.