3

我有一张这样的桌子:

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

4 回答 4

6

这是我的无 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 演示:No tiesWith ties

更新:(见评论)

于 2012-10-25T05:03:52.333 回答
3
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
于 2012-10-25T04:12:51.890 回答
1

使用公用表表达式,

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 演示

于 2012-10-25T04:05:46.533 回答
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 小提琴演示

于 2012-10-25T04:06:02.507 回答