您好我试图返回最常出现的值的记录。有了这个查询
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,9,9行,它应该返回第7行,值为3,因为它有更多的出现次数。
有人可以帮忙吗?
答案 0 :(得分: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;
答案 1 :(得分: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