2012-11-07 26 views
0

請考慮數據:自定義組通過,並把一些記錄在一個組

Id   Group   Value 
----------------------------------- 
1   1    10 
2   1    12 
3   1    10 
4   2    90 
5   2    10 
6   3    30 
7   4    12 
8   4    11 
9   5    10 
10   5    11 

我想在這個數據做Group By1,2,3發生在一組,4,5發生在另一組。我怎樣才能做到這一點SQL Server

感謝


編輯1)

我想這樣的結果:

Groups        Count 
----------------------------------------- 
Group for 1,2,3      6 
Group for 4,5       4 
+1

告訴我們你想要的結果是什麼。 –

+0

同時告訴我們[你到目前爲止所嘗試的](http://whathaveyoutried.com)。 – Oded

+0

請參閱我的編輯1.我希望通過基於「組」列的組,但是我有標準。我想在一個組中放置1,2,3,4位置,在另一個組中放置一個「4,5」 – Arian

回答

1

我使用outer apply所以你不會你的代碼複製到組

select 
    C.Group_Name, count(*) 
from Table1 
    outer apply 
    (
     select 
      case 
       when C.[Group] in (1, 2, 3) then 'Group for 1, 2, 3' 
       when C.[Group] in (4, 5) then 'Group for 4, 5' 
      end as Group_Name 
    ) as C 
group by C.Group_Name 

您還可以使用子查詢

select 
    C.Group_Name, count(*) 
from 
(
    select 
     case 
      when T.[Group] in (1, 2, 3) then 'Group for 1, 2, 3' 
      when T.[Group] in (4, 5) then 'Group for 4, 5' 
     end as Group_Name, 
     T.Value, 
     T.Id 
    from Table1 as T 
) as C 
group by C.Group_Name 
+0

你不應該這樣寫內部選擇。操作系統正在尋找組連接,而不是寫'1,2,3組'作爲' –

+0

'所以,通常的'for xml'連接可以工作。有2-3個關於連接字段每天如何到達stackoverflow的問題。我看不到分組規則(除[Group] <= 3) –

+1

是的'for xml'就可以做到這一點。但是,你必須向OP展示OP如何以這種方式或者以其他方式不按照你所做的方式寫下來。問題是他的問題不清楚,所以你不能告訴他如何按結果分組。爲什麼'1,2,3'分組在一起,而'4,5'分組到不同的組。 –

2

這也可以做你想做的:

SELECT 'Group for 1,2,3' AS GROUPS 
    , COUNT(Id) AS Count 
FROM Foo 
WHERE [Group] IN (1,2,3) 

UNION ALL 

SELECT 'Group for 4,5' AS GROUPS 
    , COUNT(Id) AS Count 
FROM Foo 
WHERE [Group] IN (4,5) 

http://sqlfiddle.com/#!6/cdb82/2/0

當然這隻有當你知道你想要哪個組。

+0

不錯。今天我有類似的問題。這工作得很好。 +1 – Demnogonis