如何获取在SQL Server中使用group By的Count()值的总和?

时间:2014-06-10 05:31:25

标签: sql-server count sum grouping

我有一个包含2个字段的表:

Datetime                     [IndexValue]
---------                    -----------
2014-02-23 20:15:59.000      G
2014-02-23 20:15:59.000      G
2014-02-23 20:15:59.000      Y
2014-03-05 12:42:59.683      R
2014-03-05 12:42:59.683      G
2014-03-05 12:42:59.683      Y
2014-03-05 12:42:59.683      G

我想按名称对它们进行分组,使用'count'和'SUM'

Datetime                 [IndexValue] amount   total
---------                -----------  ------  ------
2014-02-23 20:15:59.000  G            2       3
2014-02-23 20:15:59.000  Y            1       3
2014-03-05 12:42:59.683  G            2       4
2014-03-05 12:42:59.683  Y            1       4
2014-03-05 12:42:59.683  R            1       4

我成功使用此代码,但仅在MySQL中,SQL Server 2008中的错误

SELECT 
  CONVERT(varchar,[CreateDate],101),[IndexValue],
COUNT(*) AS amount,
(SELECT COUNT(*) AS total FROM [db_spc].[dbo].[tb_crqs_item])
FROM [db_spc].[dbo].[tb_crqs_item]
GROUP BY CONVERT(varchar,[CreateDate],101),[IndexValue]
ORDER BY CONVERT(varchar,[CreateDate],101)

如何在SQL Server中编写查询?

1 个答案:

答案 0 :(得分:1)

如果要获取子组的计数,则需要链接到主表以标识该组。 即:

SELECT 
    createdate,
    [IndexValue],
    COUNT(*) AS amount, 
    (SELECT COUNT(*) FROM tb_crqs_item t1 where t1.createdate =t0.createdate)
FROM tb_crqs_item t0
GROUP BY createdate,[IndexValue]
ORDER BY createdate