2010-11-17 77 views
3

這是我第一次發佈Stack Overflow,但已經發現它是一個非常寶貴的資源。按SQL 2005中相關子查詢的結果分組

我的問題與SQL語句組中的相關子查詢有關,我知道這是不可能的。我希望通過解釋查詢的意圖,我可能會找到一些幫助。以最簡單的形式,我試圖通過相關子查詢的結果通過主鍵和組進行聚合。用於關聯的字段對於每個主鍵記錄是唯一的。如果按照相關字段進行分組,則不會提供預期結果。我需要能夠根據相關子查詢的結果進行分組,但我不確定如何重組查詢。下面提供了一個示例查詢。

感謝

-John

SELECT DISTINCT 
    (SELECT substring(CommaDelimitedTranslatedList, 0, len(CommaDelimitedTranslatedList)) 
    FROM 
     ( 
      SELECT 
       cd.choiceValue + ',' 
      from SelectedChoiceTable sct 
       join ChoiceDescription cd on 
        cd.ChoiceID = sct.ChoiceID 
      where 
       sct.ChoiceSet = TargetJoinTable.ChoiceKey FOR XML PATH('') 
     ) D (CommaDelimitedTranslatedList)) AS   [TargetJoinTableCommaDelimitedTranslatedList1] , 
    count(BaseTable.BaseKey) 
FROM BaseTable 
    join TargetJoinTable on 
     BaseTable.BaseKey = TargetJoinTable.BaseKey 
Group By 
    [TargetJoinTableCommaDelimitedTranslatedList1] 
Order By 
    [TargetJoinTableCommaDelimitedTranslatedList1] ASC 

回答

2

乍一看,請嘗試更改子查詢的CROSS(或外部)應用。這將「列」從SELECT子句移動到FROM子句,從而允許分組。

SELECT 
    foo.TargetJoinTableCommaDelimitedTranslatedList1 , 
    count(BaseTable.BaseKey) 
FROM 
    BaseTable 
    join 
    TargetJoinTable on BaseTable.BaseKey = TargetJoinTable.BaseKey 
    CROSS APPLY 
    (
    SELECT 
     substring(CommaDelimitedTranslatedList, 0, 2000000000) 
       AS TargetJoinTableCommaDelimitedTranslatedList1 
    FROM 
     ( 
     SELECT 
      cd.choiceValue + ',' 
     from 
      SelectedChoiceTable sct 
      join 
      ChoiceDescription cd on cd.ChoiceID = sct.ChoiceID 
     where 
      sct.ChoiceSet = TargetJoinTable.ChoiceKey 
     FOR XML PATH('') 
     ) D (CommaDelimitedTranslatedList) 
    ) foo 
Group By 
    foo.TargetJoinTableCommaDelimitedTranslatedList1 
Order By 
    foo.TargetJoinTableCommaDelimitedTranslatedList1 ASC 

移入或移出聚集到派生表因此與此

SELECT 
    COUNT(foo.BaseKey), 
    TargetJoinTableCommaDelimitedTranslatedList1 
FROM 
    (SELECT DISTINCT 
     (SELECT substring(CommaDelimitedTranslatedList, 0, len(CommaDelimitedTranslatedList)) 
     FROM 
      ( 
       SELECT 
        cd.choiceValue + ',' 
       from SelectedChoiceTable sct 
        join ChoiceDescription cd on 
         cd.ChoiceID = sct.ChoiceID 
       where 
        sct.ChoiceSet = TargetJoinTable.ChoiceKey FOR XML PATH('') 
      ) D (CommaDelimitedTranslatedList)) AS   [TargetJoinTableCommaDelimitedTranslatedList1] , 
    BaseTable.BaseKey 

    FROM BaseTable 
     join TargetJoinTable on 
      BaseTable.BaseKey = TargetJoinTable.BaseKey 
    ) foo 
Group By 
    [TargetJoinTableCommaDelimitedTranslatedList1] 
Order By 
    [TargetJoinTableCommaDelimitedTranslatedList1] ASC 

一個問題將是該CSV TargetJoinTableCommaDelimitedTranslatedList1可能會產生很多次:每一次當BaseTable.BaseKey我讀這正確。這將是緩慢的。我的感覺是,CSV代應該持續到最後:您實際上是在TargetJoinTable.ChoiceKey上進行分組,而不是它生成的CSV。

+0

我使用了頂部的例子。這工作,以及改善我的整體查詢性能。 – 2010-11-17 21:36:56