乘法列

时间:2018-07-25 19:19:14

标签: sql sql-server

我下面有一个SQL脚本。

SELECT
     InvoiceNo
    ,InvoiceType
    ,Amount
    ,OrderAmount
    ,ShippingAmount
    ,TruckTaxAmount
    ,PreShippingAmount
FROM truckdb AS t1
INNER JOIN truckdetails AS t2 ON tl.truckdetail = t2.truckid
WHERE [shipping date] > = '01-01-2011'

和样本数据

+--------+-------------+---------+-------------+----------------+------------+----------+
| InvNo  | InvoiceType | Amount  | OrderAmount | ShippingAmount | TruckTxAmt | PreShAmt |
+--------+-------------+---------+-------------+----------------+------------+----------+
|    001 | ckt         |    1200 |         544 |            666 |         23 |       11 |
|    002 | tkp         |    1300 |         544 |            133 |         11 |       11 |
|    009 | ckt         |    1222 |         221 |            122 |        221 |      566 |
+--------+-------------+---------+-------------+----------------+------------+----------+

我有几种发票类型。我想显示一个特定的CKT发票类型-负数,金额,订单金额,运输金额,卡车税收金额。我试图在where子句之后使用when语句来乘法。但是出了点问题。

2 个答案:

答案 0 :(得分:2)

您需要在SELECT子句中使用CASE WHEN,而不是在WHERE子句之后:

SELECT 
...
CASE WHEN InvoiceType='CKT' THEN Amount * -1.00 ELSE Amount END AS Amount,
CASE WHEN InvoiceType='CKT' THEN OrderAmount * -1.00 ELSE OrderAmount END AS OrderAmount,
(etc)
...
FROM ...

答案 1 :(得分:0)

谢谢@Tab Alleman

SELECT ... CASE WHEN InvoiceType='CKT' THEN Amount * -1.00 ELSE    Amount END AS Amount, 
      CASE WHEN InvoiceType='CKT' THEN OrderAmount * -1.00 ELSE OrderAmount END AS 
          OrderAmount, (etc) ... FROM ...    ------------------------------------------------------------------------