2017-03-15 160 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;