sql内连接查询可以使用外部查询的值吗?

时间:2015-03-12 06:05:34

标签: mysql sql-server join

以下运行良好:

select Runs.runId,Runs.prodId,fail,Owner,
 (cast(counts.Count as decimal(4,2))) as PercentAnalysed,Language,Platform 
from Runs AS Runs Inner Join Product AS Product On Runs.prodId=Product.prodId 
    left join (SELECT COUNT(*) AS 'Count', Results.runId 
            FROM Results inner join Runs on Results.runId=Runs.runId 
            WHERE Analysed = 'True' 
            GROUP BY Results.runId ) counts on counts.runId = Runs.runId

我希望外部查询中的PercentAnalysed值如下:

= [counts.Count/failCount] if failCount !=0

=[0] if failCount=0

我该怎么做?

任何人都知道吗?

1 个答案:

答案 0 :(得分:0)

您需要使用CASE语句来获得所需内容。

SELECT 
    Runs.runId,
    Runs.prodId,
    fail, 
    Owner,
    CAST(CASE WHEN failcount <> 0 THEN counts.Count/failcount 
         WHEN failcount = 0 OR counts.Count IS NULL THEN 0
         ELSE counts.Count END AS Decimal(4,2)) PercentAnalysed,
    Language,
    Platform 
FROM
   .....