简体   繁体   中英

How to add case expression in SQL select query

I tried following query to get incoming payment details of customers. What is the wrong in this case statement? What i needed here is display payment type if it has amount.

select convert(varchar,a.DocDate,110) as DocDate,
       a.CardCode,
       a.CardName,
       d.SlpName,
       e.CheckNum,
       (case when a.CashSum >= 0 then "Cash Payment" when a.CreditSum >= 0 then "Credit Card Payment" when a.CheckSum >= 0 then "Cheque Payment" else "Bank Transfer" end) as 'Payment type',
       (ISNULL(a.CashSum,0) + ISNULL(a.CreditSum,0) + ISNULL(a.CheckSum,0) + ISNULL(a.TrsfrSum,0)) as DocTotal 
from ORCT a
left join RCT2 b on b.DocNum=a.DocNum
Left Join OINV c on c.DocNum = b.DocEntry
Left join OSLP d on d.SlpCode = c.SlpCode
left join RCT1 e on e.DocNum = a.DocEntry

It gives following error 在此处输入图片说明

In SQL Server literal strings are enclosed in single quotes ' , not double quotes " .

The column (object) names, on the other hand, are enclosed in brackets [Payment type] , or double quotes "Payment type" .

So, your query should look like:

case 
    when a.CashSum >= 0 then 'Cash Payment' 
    when a.CreditSum >= 0 then 'Credit Card Payment'
    when a.CheckSum >= 0 then 'Cheque Payment'
    else 'Bank Transfer' 
end as [Payment type]

Replace the double quotes to single quote in the following case expression in the THEN block:

(case when a.CashSum >= 0 then "Cash Payment" when a.CreditSum >= 0 then "Credit Card Payment" when a.CheckSum >= 0 then "Cheque Payment" else "Bank Transfer" end) as 'Payment type',

to

(case when a.CashSum >= 0 then 'Cash Payment' when a.CreditSum >= 0 then 'Credit Card Payment' when a.CheckSum >= 0 then 'Cheque Payment' else 'Bank Transfer' end) as 'Payment type',

Example with db<>fiddle demo:

Receiving error when using dobule quotes in THEN

Working after changed to single quotes in THEN

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM