在另一个变量中使用子查询中的计算值

时间:2013-05-10 17:17:10

标签: sql subquery

我有一个复杂的子查询,显示[Days Open]。我想将此[Days Open]用作另一个变量中的值。这是一个简化的代码示例。

如果我将整个子选择并将其粘贴到第二个subselect = [days open]的任何地方,则查询工作只需要3分钟。

我只想让第二个子查询引用第一个子查询

中的计算值
     SELECT 
Sub.Category AS 'Category',
    SubSelect(not actually value just shortening code) As [Days Open],

(Case 
When Sub.Category Like '%Part%' Then 
    (Case 
    When Cast([Days Open] As Int)>60 Then 'Late' 
    When Cast([Days Open] As Int)<61 Then 'Not Late'
    Else 'N/A' End)
When Sub.Category Like '%Determination%' Then 
    (Case 
    When Cast([Days Open] As Int)>1 Then 'Late' 
    When Cast([Days Open] As Int)<2 Then 'Not Late'
    Else 'N/A' End)
When Sub.Category Like '%History%' Then 
    (Case 
    When Cast([Days Open] As Int)>5 Then 'Late' 
    When Cast([Days Open] As Int)<6 Then 'Not Late'
    Else 'N/A' End)
When Sub.Category Like '%Eval%' Then 
    (Case 
    When Cast([Days Open] As Int)>45 Then 'Late' 
    When Cast([Days Open] As Int)<46 Then 'Not Late'
    Else 'N/A' End)
Else 'N/A' End) As 'Days Open Late'*/

    FROM Tasks As Sub
    WHERE (Sub.Status=2) And ((Sub.DateClosed Between '04/01/2013' And '04/30/2013 11:59:59 PM')) 
    Order By Sub.Category Asc, 'Days Open' Desc

1 个答案:

答案 0 :(得分:0)

我会将SubSelect向下移动到FROM子句中,将其视为虚拟表。这样,您可以在SELECT子句中多次引用其值。