tags:

views:

45

answers:

2

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  A: 

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
astander
+2  A: 
  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)

Ken White
Your code has invalid syntax:Must be "CASE WHEN PROCESSDATE BETWEEN ..."instead of "CASE PROCESSDATE WHEN BETWEEN ..."
Alex
Good catch. Fixed.
Ken White
SELECT NULL AS bar INTO #foo FROM sys.columns: what datatype is bar?
gbn
@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 White
@Ken: yes, correct, I know that. Now try it and report back ;-)
gbn
@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.
Ken White
@Ken: don't have or do Oracle
gbn
@gbn: Your query doesn't work in SQL Server 2005 Express via SMSS. I can run the SELECT, but any effort to determine the type of the column BAR results in an unhandled exception.
Ken White
@gbn: Lucky you. I'm fortunate enough not to have to do Oracle any more; I count my blessings daily. <g>
Ken White
@Ken: it's an anomaly I found some years ago: it gives me int from the table on SQL Server 2000 and 2005: SELECT NULL AS bar INTO dbo.foo; EXEC sp_help 'dbo.foo'
gbn
@gbn: Thanks. I never would have expected that behavior. However, performing your SELECT does show int as the column type of dbo.foo.bar, but "SELECT Bar + 1 AS NewBar FROM dbo.foo" returns NULL. Even with the anomaly, you can't do math using a NULL. <g>
Ken White