案例 - 何时加入表格时

时间:2013-01-16 20:54:44

标签: sql sql-server-2008 case inner-join

我有两张桌子:

AppDetailFee table has AppID (PK), TypeID, Amount
AppDetail table has AppID (PK)   

我在AppID上加入两个表,我需要检查以下是否有TypeID和金额。有3种情况:

If TypeID = 6 and Amount = 0 then  print appid and amount zero
If typeID = 6 and amount <> 0  - bypass and do not print
When TypeID <> 6 then print zero

下面是我使用的代码,btu我得到的所有行的结果都不等于零,数量为零。

任何帮助将不胜感激。 感谢

SELECT  ad.AppID
      , MAX(case when (adf.TypeID = 6 AND adf.Amount = 0) then 0 
                 when (adf.TypeID = 6 AND adf.Amount <> 0) then Adf.Amount
       ELSE 0 END) AS FeeAmount

FROM         
      AppDetail AS ad   

inner join  AppDetailFee adf ON
      ad.AppID = adf.AppID 

WHERE  adf.Amount =0

1 个答案:

答案 0 :(得分:3)

您有WHERE子句删除了不符合条件的所有内容:

WHERE  adf.Amount =0

尝试删除并运行查询:

SELECT  ad.AppID
      , MAX(case when (adf.TypeID = 6 AND adf.Amount = 0) then 0 
                 when (adf.TypeID = 6 AND adf.Amount <> 0) then Adf.Amount
                 else 0 END) AS FeeAmount
FROM  AppDetail AS ad   
inner join  AppDetailFee adf ON
      ad.AppID = adf.AppID 
group by ad.AppID

您还缺少查询中的GROUP BY子句。