如何计算SQL中另一列中每个值的模式

时间:2012-10-25 03:56:34

标签: sql-server sql-server-2008 tsql window-functions

我有一张这样的表:

ID   Group  Gender
------------------
1    A      M
2    A      M
3    A      F
4    A      M
5    A      U
6    B      F
7    B      F
8    B      M
9    C      U
10   C      F
11   C      U

我正在尝试为每个性别计算模式组。换句话说,对于每个性别,请告诉我哪个是最受欢迎的群体。所以我想要的结果如下:

Gender  ModeGroup
-----------------
M       A          (because 3 males in group A, 1 in B and 0 in C)
F       B          (because 2 females in group B, 1 in A and 1 in C)
U       C          (because 2 unknown in group C, 0 in B and 1 in C)

在平局的情况下,我需要为每个绑定组返回一条记录。

如何在TSQL中优雅地完成这项工作?我想我需要使用一个窗口函数,但我一直在努力解决它。

4 个答案:

答案 0 :(得分:5)

这是我的无CTE解决方案:

SELECT
  Gender,
  [Group]
FROM
  (
    SELECT
      [Group],
      Gender,
      RANK() OVER(PARTITION BY Gender ORDER BY [Count] DESC) AS [Rank]
    FROM
      (
        SELECT [Group], Gender, SUM(1) AS [Count]
        FROM GroupGender
        GROUP BY [Group], Gender
      ) AS counts
  ) AS ranks
WHERE
  [Rank] = 1

SQL Fiddle Demos:No tiesWith ties

更新:(见评论)

答案 1 :(得分:2)

Declare @t Table(Id Int Identity, [Group] Varchar(1),Gender Varchar(1))
    Insert Into @t Values
    ('A','M'),('A','M'),('A','F'),('A','M'),('A','U'),
    ('B','F'),('B','F'),('B','M'),
    ('C','U'),('C','F'),('C','U')

;With Cte As 
(
    Select 
        [Group]
        ,Gender
        ,GenderCount = Count(Gender)
    From @t
    Group By [Group],Gender
)

Select Gender,ModeGroup = [Group]
From (
        Select 
            *,
        Rn = Dense_Rank() Over(Partition by [Group] order by [Group],GenderCount desc)
        from Cte
     )X
Where Rn =1

<强>结果

Gender  ModeGroup
M       A
F       B
U       C

答案 2 :(得分:1)

使用Common Table Expression,

WITH results
AS
(
    SELECT  Gender, 
            [GROUP], 
            COUNT(*) totalCount,
            ROW_NUMBER() OVER (Partition BY Gender ORDER BY COUNT(*) DESC) a
    FROM table1
    GROUP BY Gender, [GROUP]
)
SELECT Gender, [GROUP]
FROM RESULTs
WHERE a = 1
-- ORDER BY [GROUP]

SQLFiddle Demo

答案 3 :(得分:0)

这样的东西
;WITH Vals AS (
        SELECT  Gender,
                [Group],
                COUNT([Group]) Cnt
        FROM    Table1
        GROUP BY Gender,
                [Group]
)
, ValsID AS (
        SELECT  *,
                ROW_NUMBER() OVER (PARTITION BY Gender ORDER BY Cnt DESC) RowID
        FROM    Vals
)
SELECT  Gender,
        [Group]
FROM    ValsID
WHERE   RowID = 1

SQL Fiddle DEMO