2017-03-15 126 views
0

嗨我試圖返回的記錄最有價值的事件。有了這個查詢只返回最高價值記錄

SELECT b.section,c.valuename 
     ,count(a.value) as counts 

    FROM [dbo].[SurveyResponse] a 
    JOIN [dbo].[Questions] b ON A.qid=b.qid 
    join [dbo].[SurveyValues] c on a.value=c.value 
    where profileid=2 
    group by b.section,c.valuename 
    order by 1,2 

我得到這些結果(Original Image):

+ -- + ----------------------- + ----------------- + ------ + 
| | section     | valuename   | counts | 
+ -- + ----------------------- + ----------------- + ------ + 
| 1 | Customer & Markets  | Completely Agree | 2  | 
| 2 | Customer & Markets  | Somewhat Agree | 4  | 
| 3 | Data and Analytics  | Completely Agree | 3  | 
| 4 | Data and Analytics  | Somewhat Disagree | 3  | 
| 5 | Leadership & Culture | Completely Agree | 2  | 
| 6 | Leadership & Culture | Somewhat Agree | 4  | 
| 7 | Organization & Talent | Completely Agree | 3  | 
| 8 | Organization & Talent | Somewhat Agree | 2  | 
| 9 | Organization & Talent | Somewhat Disagree | 1  | 
| 10 | Products & Services  | Completely Agree | 3  | 
| 11 | Products & Services  | Somewhat Agree | 1  | 
| 12 | Products & Services  | Somewhat Disagree | 2  | 
| 13 | Technology & Innovation | Completely Agree | 3  | 
| 14 | Technology & Innovation | Somewhat Agree | 5  | 
| 15 | Vision & Strategy  | Completely Agree | 2  | 
| 16 | Vision & Strategy  | Somewhat Agree | 4  | 
+ -- + ----------------------- + ----------------- + ------ + 

從這個結果,我想與計數的中值返回段和值名稱。例如,第7,8,9行,它應該返回值爲3的行7,因爲它有更多的出現次數。

有人可以幫忙嗎?

+0

中位數不是他值最多的事件。樣本數據和期望的結果將闡明你正在嘗試做什麼。 –

+0

也許正在尋找模式 – maSTAShuFu

+0

或者可能從模式結果中尋找中位數......對於行3 4 7 10 13的計數3(模式),因此模式的中位數爲7 – maSTAShuFu

回答

0

如果你把你的查詢放在CTE中,那麼你可以使用相關的子查詢來獲得你想要的結果。

; with 
    CTE as (-- CTE 
     SELECT b.section 
       , c.valuename 
       , count(a.value) as counts 
      FROM [dbo].[SurveyResponse] a 
      JOIN [dbo].[Questions] b ON A.qid=b.qid 
      join [dbo].[SurveyValues] c on a.value=c.value 
      where profileid=2 
      group by b.section,c.valuename 
    ) 
select Section, ValueName, counts 
    from CTE a 
    where ValueName = (-- Correlated Subquery 
     select top 1 ValueName 
      from CTE b 
      where a.Section = b.Section 
      order by counts desc 
    ) 
    order by Section 
1

讓我假設 - 基於示例 - 您希望每個部分的最高計數。這是一個窗口函數的簡單應用:

select x.* 
from (select q.section, c.valuename, count(sr.value) as counts, 
      row_number() over (prtition by q.section order by count(sr.value) desc) as seqnum 
     from [dbo].[SurveyResponse] sr join 
      [dbo].[Questions] q 
      on sr.qid = q.qid join 
      [dbo].[SurveyValues] sv 
      on sr.value = sv.value 
     where profileid = 2 
     group by q.section, c.valuename 
    ) x 
where seqnum = 1;