不同列的条件计算
Conditional calculation on different columns
我有这个 table,我需要在 SQL Server
中计算不同的列
到目前为止,我已经能够使用此公式 line_item_total_including_gst / 11
计算 line_item_total_gst
列,使用以下行为空的语法:
UPDATE dbo.invoice_info
SET line_item_total_gst = line_item_total_including_gst / 11
WHERE line_item_total_gst IS NULL;
我的问题是如何根据条件进行计算,例如,如果 gst_applicable
列等于 'Yes',则执行上面的计算。否则,如果 gst_applicable
等于 'No',则 line_item_total_gst
为 0。
您可以使用 case
表达式:
UPDATE dbo.invoice_info
SET line_item_total_gst =
CASE gst_applicable WHEN 'Yes' THEN line_item_total_including_gst / 11
ELSE 0
END
WHERE line_item_total_gst IS NULL;
您可以试试这个更新:
UPDATE dbo.invoice_info
SET line_item_total_gst = line_item_total_including_gst / 11
WHERE line_item_total_gst IS NULL AND gst_applicable ='YES';
UPDATE dbo.invoice_info
SET line_item_total_gst = 0
WHERE line_item_total_gst IS NULL AND gst_applicable ='No';
如果要selecttable带计算:
SELECT
gst_applicable
,line_item_total_excluding_gst
,CASE WHEN gst_applicable = 'Yes' AND line_item_total_gst IS NULL
THEN line_item_total_including_gst / 11
WHEN gst_applicable = 'Yes' AND line_item_total_gst IS NOT NULL
THEN line_item_total_gst
ELSE
0
END AS line_item_total_gst
,line_item_total_including_gst
FROM dbo.invoice_info
我有这个 table,我需要在 SQL Server
中计算不同的列到目前为止,我已经能够使用此公式 line_item_total_including_gst / 11
计算 line_item_total_gst
列,使用以下行为空的语法:
UPDATE dbo.invoice_info
SET line_item_total_gst = line_item_total_including_gst / 11
WHERE line_item_total_gst IS NULL;
我的问题是如何根据条件进行计算,例如,如果 gst_applicable
列等于 'Yes',则执行上面的计算。否则,如果 gst_applicable
等于 'No',则 line_item_total_gst
为 0。
您可以使用 case
表达式:
UPDATE dbo.invoice_info
SET line_item_total_gst =
CASE gst_applicable WHEN 'Yes' THEN line_item_total_including_gst / 11
ELSE 0
END
WHERE line_item_total_gst IS NULL;
您可以试试这个更新:
UPDATE dbo.invoice_info
SET line_item_total_gst = line_item_total_including_gst / 11
WHERE line_item_total_gst IS NULL AND gst_applicable ='YES';
UPDATE dbo.invoice_info
SET line_item_total_gst = 0
WHERE line_item_total_gst IS NULL AND gst_applicable ='No';
如果要selecttable带计算:
SELECT
gst_applicable
,line_item_total_excluding_gst
,CASE WHEN gst_applicable = 'Yes' AND line_item_total_gst IS NULL
THEN line_item_total_including_gst / 11
WHEN gst_applicable = 'Yes' AND line_item_total_gst IS NOT NULL
THEN line_item_total_gst
ELSE
0
END AS line_item_total_gst
,line_item_total_including_gst
FROM dbo.invoice_info