2014-09-28 80 views
2

如何仅对选择查询中的某些顶部选定列进行分组?分组仅由某些列表组成

一个错误但很容易的答案我会想到的是这段代码;

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 

在上述结果我得到的品牌之一后,另一起甚至thuo计数不decending。

我已经尝试过,并且我得到的最接近的是这个代码;

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 

如果我尝试使用“由COUNT(*)秩序,品牌”我知道,出于某种原因,该品牌在递减计数值的顺序regardles。它接缝喜欢它只订购品牌列,而不是品牌和数量

我也尝试在同一张桌子上做一个左连接,这样我只需要在主表中的分组依据,但那不是正确的,我想出的代码真是令人困惑,所以我将在此主题之外留下。

非常感谢您的帮助。

回答

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 
+0

点上。这做了我以后的事情。我确实需要为count(*)添加一个名称才能工作。 (count(*)AS numberofjeans)。非常感谢FuzzyTree – Slint 2014-09-29 21:52:43

0

试试这个

select TOP 5 t1.* from (SELECT brand, name, delivered, count(*)as 'test' 
From myTB 
Where type = 'jeans' 
Group By brand, name,delivered 

)为T1 ORDER BY t1.test递减

+0

试过但我收到以下错误; Msg 1033,Level 15,State 1,Line 5 除非还指定了TOP,OFFSET或FOR XML,否则ORDER BY子句在视图,内联函数,派生表,子查询和公用表表达式中无效。 – Slint 2014-09-28 23:03:34

+0

我编辑答案现在尝试,我把订单出子查询 – 2014-09-28 23:11:07