SQL Server:当记录为1时选择,然后返回行,否则返回0记录

时间:2018-05-30 13:55:23

标签: sql-server tsql

我需要一些查询帮助。

我写了一个脚本,它带回了一个订单号和所需的容器数量(代码如下):

SELECT
    CONI.CONTNO,
    CONI.ITEMNO,
    CONI.[WEIGHT],
    CONI.QTY,
    STOK.PGROUP,
    CASE WHEN CPRO.TNTCOL = 1 THEN 1
         WHEN CPRO.TNTCOL = 0 THEN 0
         WHEN CPRO.TNTCOL IS NULL THEN 0 END AS [TNT],
    CONI.RECID,
    CPRO.RECKEY
INTO
    #SUB
FROM
    ContItems CONI
LEFT JOIN 
    ContractItemProfiles CPRO ON CONI.RECID = CPRO.RECKEY
JOIN 
    Stock STOK ON CONI.ITEMNO = STOK.ITEMNO
WHERE
    STOK.PGROUP LIKE 'FLI%'


SELECT
    #SUB.CONTNO,
    #SUB.TNT,
    SUM(#SUB.QTY) AS [Number of flight cases]
FROM
    #SUB
WHERE
    #SUB.CONTNO = '123/321581'
GROUP BY
    #SUB.CONTNO,
    #SUB.TNT

DROP TABLE #SUB

我得到了这个结果:

Contno      TNT    Number of flight cases
------------------------------------------
123/321581   0     20.00
123/321581   1      1.00

如果TNT列中没有1,我需要有条件地恢复具有TNT = 1 Else的行然后将记录带回0

我希望这个解释得足够。

1 个答案:

答案 0 :(得分:1)

该案例可以替换为

isnull(CPRO.TNTCOL, 0) 


select top 1 
from ( SELECT #SUB.CONTNO,
              #SUB.TNT,
              SUM(#SUB.QTY) AS [Number of flight cases]
         FROM #SUB
        WHERE #SUB.CONTNO = '123/321581'
     ) t 
order by TNT desc