简体   繁体   中英

CASE statement IF ELSE in SQL Server

I have this select statement and what I am trying to accomplish is to get data in the
DosagePerUnits column only if Dosage is not equal to empty or 1 and if Units is not empty or 1.

Can someone help me please ?

select 
    sbd.Code, c.Description, sbd.Dosage, 
    Case 
        when sbd.Units = '' then '1' 
        else sbd.Units 
    end as Units, 
    ad.ApptDate, sbd.RCycle, sbd.RWeek, sbd.RDay, 
    t.HistoryOrder, t.TypeId, sbd.Dosage + '/' + sbd.UnitsAS DosagePerUnits
from
    bill_SuperBillDetail sbd, 
    bill_ProcedureVerification pv, 
    AppointmentData ad,
    CPTCode c, 
    CPTType t
where 
    sbd.AccessionNumber = pv.AccessionNumber
    and pv.ApptId = ad.ApptId
    and ad.PatientId = 443
    and ad.ApptDate <= GETDATE()
    and ad.ApptDate > '2009-11-15 00:00:00.000'
    and c.TypeId = t.TypeId

According to your description, it should be like this:

CASE WHEN ISNULL(sbd.Dosage, '1') <> '1' AND ISNULL(sbd.Units, '1') <> '1' THEN
sbd.Dosage + '/' + sbd.Units
ELSE NULL END AS DosagePerUnits

ISNULL(x, 1) replaces x with 1 if it is null. So ISNULL(x, 1) is = 1 if x is either 1 or NULL.

EDIT: Changed to the assumption that [Dosage] and [Unit] are both varchar as your comment indicates.

如果sbd.Units =''则为Case,而不是Case,否则sbd.Units以Units结尾,请尝试Coalesce(sbd.Units,1)作为Units,

If any part of the calculation is null the whole thing will be null. You can use this fact this way:

nullif(nullif(sbd.Dosage, ''), '1') + '/' + nullif(nullif(sbd.Units, ''), '1') AS DosagePerUnits

This will result in DosagePerUnits being null when one of the columns are '', '1' or null

I thought i had a really clever answer here. Oh well, I guess it wasn't that clever. Does anyone know why I am unable to write comments ?

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