按多列分组,在第一个按列分组的SUM

时间:2013-03-17 05:51:02

标签: sql sql-server-2008 tsql

我正在编写一个分组超过两列的查询。这意味着,它会将Col1和Col2放在同一组中。

如何根据Group Col1进行记录总结?

到目前为止我有这个:http://sqlfiddle.com/#!3/eada2/1

谢谢

3 个答案:

答案 0 :(得分:0)

我能够解决它如下:

WITH cteActivityIds (activityId, allDocuByActivity)
AS
  (SELECT activityId, COUNT(*) AS allDocuByActivity FROM #ER GROUP BY activityId)
SELECT
      E.activityId AS [Actiivty ID],
      docuType AS [Docu Type],
      COUNT(docuType),
      CONVERT(DECIMAL(16,2), (COUNT(docuType) * 100.00 / t.allDocuByActivity)) [Total     DocuType in Activity],
      SUM(CASE WHEN [sent] != '1-1-1900' THEN 1 END) AS [Sent],
      SUM(CASE WHEN [approved] != '1-1-1900' THEN 1 END) AS [Approved]
FROM
      #ER AS E
INNER JOIN cteActivityIds AS t 
  ON E.activityId = t.activityId
GROUP BY
     E.activityId, docuType, t.allDocuByActivity

谢谢

答案 1 :(得分:0)

这是一个解决方案,在我看来,看起来更清洁一点 - 它不需要连接并使用'partition by'来计算个别计数:

WITH activityCounts as (
    select
        activityId,
        docuType,
        count(activityId) OVER(PARTITION BY activityId) as activityIdCount,
        count(docuType) OVER(PARTITION BY activityId, docuType) as docuTypeCount,
        SUM(CASE WHEN [sent] != '1-1-1900' THEN 1 END) OVER(PARTITION BY activityId, docuType) AS [Sent],
        SUM(CASE WHEN [approved] != '1-1-1900' THEN 1 END) OVER(PARTITION BY activityId, docuType) AS [Approved]
    from ER
)
SELECT
    activityId,
    docuType,
    docuTypeCount,
    CONVERT(DECIMAL(16,2), (COUNT(docuTypeCount) * 100.00 / activityIdCount)) as [Total DocuType in Activity],
    [Sent],
    [Approved]
FROM activityCounts
GROUP BY
    activityId,
    docuType,
    activityIdCount,
    docuTypeCount,
    [Sent],
    [Approved]

这是link to sqlfiddle

答案 2 :(得分:0)

您只需要在t.allDocuByActivity

上添加一个聚合函数
MIN(t.allDocuByActivity) AS [Total DocuType in Activity],

但是,由于您的标签为DocuType。你不需要DISTINCT吗?