使用SQL Server基于列过滤记录

时间:2018-02-22 19:17:17

标签: sql-server

我有一个这样的查询,它将返回两条记录,一条在VendorCode和VendoroffsetAccount中为NULL,另一条在有效值中。我想要一种方法来获取非空记录,如果有两个记录。否则记录为NULL而不使用临时表。任何帮助将不胜感激。

    SELECT DISTINCT  ift.BatchGuid AS ProcessId ,
                'H' AS RecordType ,
                ISNULL(ift.SuperBranch, cd.SuperBranch) AS SuperBranch ,
                ISNULL(ift.ProcessName, cd.ProcessName) AS ProcessName ,
                VendorOffsetAccount = CASE WHEN ift.OffsetType = 'V'
                THEN ISNULL(ift.VendorOffsetAccount,
                cd.VendorOffsetAccount)
                END ,
                VendorCode = CASE WHEN ift.OffsetType = 'V'
                THEN ISNULL(ift.VendorCode, cd.VendorCode)
                END                    
                FROM    IFP.InboundFileTransaction ift
                CROSS APPLY IFP.ctlConfigDefault cd
                WHERE   CAST(BatchGuid AS CHAR(36)) = '67C6A9C3-F8B7-45ED-8DDD-0AB6701BED34'

以下是此查询的示例输出。

     Id   Type      SB   Name    VendorOffsetAccount        VendorCode
      1     H       XYZ  UPLOAD  NULL                       NULL
      1     H       XYZ  UPLOAD  XYZ000123                  DFEE      

先谢谢

1 个答案:

答案 0 :(得分:2)

如果您想要一条记录,并且更喜欢非null值,那么您可以使用toporder by

select top 1
    ift.BatchGuid as ProcessId
  , 'H' as RecordType
  , isnull(ift.SuperBranch, cd.SuperBranch) as SuperBranch
  , isnull(ift.ProcessName, cd.ProcessName) as ProcessName
  , VendorOffsetAccount = case when ift.OffsetType = 'V' then isnull(ift.VendorOffsetAccount, cd.VendorOffsetAccount) end
  , VendorCode = case when ift.OffsetType = 'V' then isnull(ift.VendorCode, cd.VendorCode) end
from ifp.InboundFileTransaction ift
  cross apply ifp.ctlConfigDefault cd
where cast(BatchGuid as char(36)) = '67C6A9C3-F8B7-45ed-8ddd-0ab6701bed34'
order by case when ift.OffsetType = 'V' then isnull(ift.VendorCode, cd.VendorCode) end desc