【问题标题】:Using aggregate function but don't want to group by the specific column使用聚合函数但不想按特定列分组
【发布时间】:2014-05-17 20:58:48
【问题描述】:

当我这样做时:

select firstpartno,count(firstpartno) 
from dbo.vw_Split4 
group by firstpartno

效果很好。

我想要两个新列 nMaleCountnFemaleCount。这些将分别是 M 和 F 的计数(firstpartno)。但是计数迫使我按性别分组,这是我不想要的。我想做所有这些并有我的四列,但仅按 firstpartno 分组。请帮忙解决这个问题!

vw_Split4如下:

firstpartno     Sex
     1           M
     2           F
     2           F
     3           M
     5           M
     2           M

我希望之后是这样的:

firstpartno     Sex     nMaleCount     nFemaleCount
     1           M
     2           F
     2           F
     3           M
     5           M
     2           M

非常感谢!

【问题讨论】:

    标签: sql-server-2008 aggregate-functions calculated-columns


    【解决方案1】:

    如果我正确理解你的问题,你宁愿这样做:

    SELECT firstpartno, Sex, COUNT(firstpartno)
    GROUP BY firstpartno, Sex
    

    除非出于某种原因您想将 M 和 F 的计数分成 2 列...

    【讨论】:

      【解决方案2】:

      您可以对 CASE 语句求和:

      select firstpartno
            ,count(firstpartno)
            ,sum(case when sex = 'm' then 1 else 0 end) nMaleCount
        from dbo.vw_Split4 
       group by firstpartno
      

      【讨论】:

      • 非常感谢卡尔。这很好用!正是我需要的。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-11
      • 1970-01-01
      • 2015-08-03
      • 2014-05-29
      • 1970-01-01
      • 1970-01-01
      • 2016-10-02
      相关资源
      最近更新 更多