How to select data from 30 days?

118,112

Solution 1

You should be using DATEADD is Sql server so if try this simple select you will see the affect

Select DATEADD(Month, -1, getdate())

Result

2013-04-20 14:08:07.177

in your case try this query

SELECT name
FROM (
SELECT name FROM 
Hist_answer
WHERE id_city='34324' AND datetime >= DATEADD(month,-1,GETDATE())
UNION ALL
SELECT name FROM 
Hist_internet
WHERE id_city='34324' AND datetime >= DATEADD(month,-1,GETDATE())
) x
GROUP BY name ORDER BY name

Solution 2

Try this : Using this you can select date by last 30 days,

SELECT DATEADD(DAY,-30,GETDATE())

Solution 3

For those who could not get DATEADD to work, try this instead: ( NOW( ) - INTERVAL 1 MONTH )

Share:
118,112

Related videos on Youtube

Alex N
Author by

Alex N

Updated on July 09, 2022

Comments

  • Alex N
    Alex N almost 2 years

    I have query:

    SELECT name
    FROM (
    SELECT name FROM 
    Hist_answer
    WHERE id_city='34324' AND datetime >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH)
    UNION ALL
    SELECT name FROM 
    Hist_internet
    WHERE id_city='34324' AND datetime >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH)
    ) x
    GROUP BY name ORDER BY name
    

    But DATE_SUB is a MySQL function and I need function for MsSQL 2008

    Tell me please how to select data from 30 days by using MsSQL 2008?

    P.S.: Data type of datetime is smalldatetime

  • Raab
    Raab about 11 years
    Try Again, Query changed, since you last copied
  • Arun Basil Lal
    Arun Basil Lal about 2 years
    Thank you. Worked for me and I feel this makes the SQL more readable.