用于添加字段并根据其他字段填充值的SQL语句

时间:2012-06-16 09:20:15

标签: sql

我想在我的查询中添加一个额外的字段,根据字段(CheckNum)是否返回支票号,该字段的值为“Cash”或“check”。

SELECT t1.DocNum, t0.DocDate, t0.CardName, t0.CardCode, t1.CheckNum, t0.DocTotal
FROM   OVPM t0 INNER JOIN
VPM1   t1 ON t1.docnum = t0.docnum LEFT OUTER JOIN
OACT   t2 ON t2.AcctCode = t1.CheckAct

UNION ALL

SELECT t1.DocNum, t0.DocDate, t0.CardName, t0.CardCode, t1.CheckNum, t0.DocTotal
FROM   ORCT t0 INNER JOIN
       RCT1 t1 ON t1.docnum = t0.docnum LEFT OUTER JOIN
       OACT t2 ON t2.AcctCode = t1.CheckAct

上述查询的示例结果:

                                          CheckNum     DocTotal
3   Alibhai shariff & Sons Ltd  S0003     67901        39663.000000
5   Silverstone Tyres (K) Ltd   S0191     0            93200.000000
6   Lam Limited                 S0167     1372         66380.000000
7   Osho Chemicals Industries   S0198     0            21100.000000

我想要的是什么:

                                          CheckNum     DocTotal           PayType
3   Alibhai shariff & Sons Ltd  S0003     67901        39663.000000       Check
5   Silverstone Tyres (K) Ltd   S0191     0            93200.000000       Cash
6   Lam Limited                 S0167     1372         66380.000000       Check
7   Osho Chemicals Industries   S0198     0            21100.000000       Cash

任何帮助表示感谢。

1 个答案:

答案 0 :(得分:1)

您可以在此处使用CASE。像这样 -

SELECT t1.DocNum, t0.DocDate, t0.CardName, t0.CardCode, t1.CheckNum, t0.DocTotal,
       CASE WHEN t1.CheckNum = 0 THEN 'Cash' ELSE 'Check' END AS PayType
FROM   OVPM t0 INNER JOIN
       VPM1   t1 ON t1.docnum = t0.docnum LEFT OUTER JOIN
       OACT   t2 ON t2.AcctCode = t1.CheckAct

UNION ALL

SELECT t1.DocNum, t0.DocDate, t0.CardName, t0.CardCode, t1.CheckNum, t0.DocTotal,
       CASE WHEN t1.CheckNum = 0 THEN 'Cash' ELSE 'Check' END AS PayType
FROM   ORCT t0 INNER JOIN
       RCT1 t1 ON t1.docnum = t0.docnum LEFT OUTER JOIN
       OACT t2 ON t2.AcctCode = t1.CheckAct