有条件的sql帮助

时间:2009-11-23 17:27:17

标签: sql sql-server

尝试执行条件sql查询。我的格式不正确。有什么建议?任何帮助将不胜感激。

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 个答案:

答案 0 :(得分:2)

而是尝试使用案例陈述

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

答案 1 :(得分:2)

  1. 您不能使用NULL求和,因为NULL不是数字。改为使用0。

  2. 不要使用IF。使用CASE:

    SUM(CASE   在'2009-08-01 00:00:00.000'和'2009-10-31 23:59:00.000'之间进行处理时   那么getskusold.sprice   ELSE 0 END)