代码之家  ›  专栏  ›  技术社区  ›  John

T-SQL 2005:计算符合条件的所有行和行

  •  1
  • John  · 技术社区  · 16 年前

    下面是场景:

    我有一个3列的表:“键列”、“子键列”和“布尔列”,其中前两个是表的主键。

    For my query, I'd like to count the number of rows there are for any given value in 'KeyColumn', and I'd also like to know which ones have a value of true for 'BooleanColumn'. My initial thought was to create a query like this:

    SELECT
       COUNT(*)
       ,COUNT(CASE WHEN BooleanColumn = 1 THEN 1 ELSE 0 END)
    FROM
       MyTable
    GROUP BY
       KeyColumn
    

    However, the 2nd part does not work (I'm not entirely sure why I thought it would to begin with). Is it possible to do something like this in one query? Or am I going to need to do multiple queries to make this happen?

    3 回复  |  直到 16 年前
        1
  •  5
  •   Phil Sandler    16 年前

    在第二部分中将count改为sum。;)

        2
  •  2
  •   ToxicAvenger    16 年前

    …CASE WHEN BooleanColumn = 1 THEN 1 ELSE 无效的 结束…

    count对非空行进行计数。

        3
  •  0
  •   Dingels35    16 年前

    你也可以做sum(cast(booleancolumn as tinyint))。