0

Trying to perform a conditional sql query. My formatting is incorrect. Any suggestions? Any help would be appreciated.

Select misc,

    SUM(IF(processdate BETWEEN '2009-08-01 00:00:00.000' AND '2009-10-31 23:59:00.000', getskusold.sprice, NULL) ) AS totalprice_date1,
    SUM(IF(processdate BETWEEN '2009-11-01 00:00:00.000' AND '2009-12-31 23:59:00.000', getskusold.sprice, NULL) ) AS totalprice_date2

from
misc_table

2 Answers 2

2

Rather try using a case statement

Select misc,

        SUM(CASE WHEN processdate BETWEEN '2009-08-01 00:00:00.000' AND '2009-10-31 23:59:00.000' THEN getskusold.sprice ELSE 0 END ) AS totalprice_date1,
        SUM(CASE WHEN processdate BETWEEN '2009-11-01 00:00:00.000' AND '2009-12-31 23:59:00.000' THEN getskusold.sprice ELSE 0 END ) AS totalprice_date2

    from
    misc_table
GROUP BY misc
Sign up to request clarification or add additional context in comments.

Comments

2
  1. You can't sum using NULL, as NULL isn't a numeric. Use 0 instead.

  2. Don't use IF. Use CASE:

    SUM(CASE WHEN PROCESSDATE BETWEEN '2009-08-01 00:00:00.000' AND '2009-10-31 23:59:00.000' THEN getskusold.sprice ELSE 0 END)

10 Comments

Your code has invalid syntax: Must be "CASE WHEN PROCESSDATE BETWEEN ..." instead of "CASE PROCESSDATE WHEN BETWEEN ..."
SELECT NULL AS bar INTO #foo FROM sys.columns: what datatype is bar?
@gbn: It's NULL. It has no datatype. NULL means "no known value". NULL <> NULL in a query, as one unknown can't be equivalent to another unknown (how could they be - they're unknown?).
@Ken: yes, correct, I know that. Now try it and report back ;-)
@gbn: Perhaps you should try running "SELECT NULL + 1 AS bar" on SQL Server; add "FROM dual" for Oracle. What result do you get? I get an error message about the SELECT being invalid.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.