HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Getting SQL server to recognise a date column

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
columnsqlgettingdaterecogniseserver

Problem

I am trying to get a count of IDS on a orders table for yesterday (not hardcode) where the date in the table corresponds to when the order was placed.

My table looks like this

orders (
order_id INT PRIMARY KEY
, user_id INT
, date_created DATE
, order_value FLOAT
, city_id INT
)


I have used this code to get todays date in the table -

Select *,DATEADD(dd, DATEDIFF(dd, 0, getdate()), 0) as Today
From orders


This works fine but when I try attempt a where clause below this

Select *,DATEADD(dd, DATEDIFF(dd, 0, getdate()), 0) as Today
From orders
where Today -1 = date_created;


I receive this error "Invalid column name 'Today'"
So my question is simply how can I get this table to recognise the the date I added as a new column and allow me to perform work on it?

Thanks in advance

Solution

I receive this error "Invalid column name 'Today'"

You can't reference the Today expression in the WHERE clause because the WHERE clause is evaluated before the SELECT clause according to the logical order of query processing.

Since your desired type is date, it would be better to use CAST or CONVERT rather than the DATEADD...DATEDIFF ugliness (common before SQL Server 2008 introduced the date datatype). Also, you need to use DATEADD to calculate yesterday's date instead of a subtraction operator.

The example below uses these techniques to get the orders from yesterday:

SELECT
      order_id
    , user_id
    , date_created
    , order_value
    , city_id
    , CAST(GETDATE() AS date) as Today
FROM dbo.orders
WHERE DATEADD(day, -1, CAST(GETDATE() AS date)) = date_created;

Code Snippets

SELECT
      order_id
    , user_id
    , date_created
    , order_value
    , city_id
    , CAST(GETDATE() AS date) as Today
FROM dbo.orders
WHERE DATEADD(day, -1, CAST(GETDATE() AS date)) = date_created;

Context

StackExchange Database Administrators Q#223906, answer score: 5

Revisions (0)

No revisions yet.