如何在我的选择查询中仅对一些顶部选定列进行分组?
我想到的一个错误但简单的答案就是这段代码;
SELECT TOP 5 brand, name, delivered, count(*)
From myTB
Where type = 'jeans'
Group By brand, name
Order By Count(*) DESC
我之后的结果应该返回以下结果; (上面的代码错误并返回错误)
Brand name Delivered Count
-------------------------------------
Levis 304 Slim 9/24 44
Croccer 500 Lose 3/14 22
Croccer 400 Botcut 4/7 14
Lee Botcut 33 5/5 16
Lee Slim 44 10/7 12
在上面的结果中,即使计数没有下降,我也会将这些品牌一个接一个地放在一起。
我尝试过,最接近的是这段代码;
SELECT TOP 5 brand, name, delivered, count(*)
From myTB
Where type = 'jeans'
Group By brand, name, delivered
Order By Count(*) DESC
但是返回这样的数据;
Brand name Delivered Count
-------------------------------------
Levis 304 Slim 9/24 44
Croccer 500 Lose 3/14 22
Lee Botcut 33 5/5 16
Croccer 400 Botcut 4/7 14
Lee Slim 44 10/7 12
如果我尝试使用"按计数排序(*),品牌"由于某种原因,我得到的品牌按计数值的降序排列。它只是订购品牌专栏,而不是品牌和数量
我也尝试在同一个表上进行左连接,这样我只需要在主表中进行分组,但那也不对,而我提出的代码实在令人困惑,所以我要去把它留在这个线程之外。
答案 0 :(得分:2)
您似乎想要按照每个品牌的最大数量和品牌次数进行排序。
select top 5 t1.* from (
select brand, name, delivered, count(*)
from myTB
where type = 'jeans'
group by brand, name, delivered
) t1 join (
select brand, cnt
from (
select brand, cnt,
row_number() over (partition by brand order by cnt desc) rn
from (select brand, count(*) cnt from myTB group by brand, name, delivered) t1
) t1
where rn = 1
) t2 on t1.brand = t2.brand
order by t2.cnt desc, t2.brand
答案 1 :(得分:0)
试试这个
select TOP 5 t1.* from (SELECT brand, name, delivered, count(*)as 'test'
From myTB
Where type = 'jeans'
Group By brand, name,delivered
)由t1.test desc
命令为t1