带有if的sql语句在里面吗?

时间:2015-04-21 20:54:38

标签: sql

我有以下sql查询可行。但是,我需要有/ 10000计算字段的帮助。有时候字段中没有数据要计算,所以下面的查询返回0.我如何检查数据>在执行/ 10000计算之前是否为0?

SELECT
timesheet.customerID,
customer.customer,
timesheet.projectID,
project.project_title,
timesheet.chargeID,
charge.charge_description,
timesheet.notes,
timesheet.mon/10000,
timesheet.tues/10000,
timesheet.wed/10000,
timesheet.thurs/10000,
timesheet.fri/10000,
timesheet.sat/10000,
timesheet.sun/10000,
timesheet.lineID

FROM
timesheet_line timesheet
LEFT JOIN customer ON timesheet.customerID = customer.customerID
LEFT JOIN project ON timesheet.projectID = project.projectID
LEFT JOIN charge_rate charge ON timesheet.chargeID = charge.chargeID

WHERE
timesheet.timesheetID = '" & tTimesheetID & "' --VBA variable added here

ORDER BY
timesheet.lineID

2 个答案:

答案 0 :(得分:1)

您有几个选择:

  • 当您想将可能的COALESCE值转换为其他值时,NULL函数是完美的:

    COALESCE(NullableColumn / 10000, DefaultValueIfNull)
    -- btw., NULL divided by 10,000 should yield NULL, not 0.
    
  • 某些SQL方言(例如SQL Server的T-SQL)具有非常类似的函数ISNULL

  • CASE更接近if

    CASE WHEN NullableColumn IS NOT NULL THEN NullableColumn / 1000 ELSE DefaultValue END
    

答案 1 :(得分:1)

你可以这样做(示例栏)

CASE timesheet.wed > 0 THEN timesheet.wed/10000 ELSE null END as wed,

如果值可以为null,则必须执行此操作:

CASE COALESCE(timesheet.wed,0) > 0 THEN timesheet.wed/10000 ELSE null END as wed,