我正在编写一个分组两列的查询。这意味着,它将把 Col1 和 Col2 放在同一个组中。
如何根据 Group Col1 对记录进行 SUM?
到目前为止我有这个:http ://sqlfiddle.com/#!3/eada2/1
谢谢
我正在编写一个分组两列的查询。这意味着,它将把 Col1 和 Col2 放在同一个组中。
如何根据 Group Col1 对记录进行 SUM?
到目前为止我有这个:http ://sqlfiddle.com/#!3/eada2/1
谢谢
在我看来,这是一个看起来更简洁的解决方案 - 它不需要连接并使用“分区依据”来计算个人计数:
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]
我能够解决它如下:
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
谢谢
你只需要放一个聚合函数t.allDocuByActivity
MIN(t.allDocuByActivity) AS [Total DocuType in Activity],
但是,由于您的标签是DocuType
. 你不需要DISTINCT
吗?