以下是我正在运行的查询,以获取给定对象的每个键的每个值的计数:
SELECT key, value, COUNT(value)
FROM keyval kv
WHERE object_id = 123456
GROUP BY kv.key, kv.value
ORDER BY kv.key, kv.value;
我查询的表非常简单。它只是:
object_id BIGINT
key VARCHAR(45)
value VARCHAR(45)
所以我得到的价值如下:
Color Red 26
Color Blue 24
Shape Circle 14
Shape Square 12
所以我想解析Blue和Square的结果,但保留Red和Circle的结果。这可能吗?
答案 0 :(得分:2)
我会在子查询或cte:
中使用row_numberselect
[key],
value,
cnt
from (
select
[key],
value,
count(*) as cnt,
row_number() over(partition by [key] order by count(*) desc) rnk
from keyval
where object_id = 123456
group by
[key],
value
) kv
where rnk = 1
答案 1 :(得分:1)
试试这个,但要注意红色和蓝色都有26个数字的情况......两者都会被退回。
with cte as
(select k,v,count(v) c
from #kvp
group by k,v)
select results.*
from
cte restults
inner join (select k, max(c) m from cte group by k) filter
on restults.k = filter.k
where
filter.m = restults.c
and id = @id
答案 2 :(得分:0)
试试这个。
SELECT KEY,
value,
Max(cnt)
FROM (SELECT KEY,value,Count(value) As cnt
FROM keyval kv
WHERE object_id = 123456
GROUP BY kv.KEY,kv.value
ORDER BY kv.KEY Desc,kv.value Desc
) a
GROUP BY a.KEY