SQL查询帮助 - 如何分组条目数

时间:2011-10-25 19:40:50

标签: sql

鉴于以下数据,我想计算每个组中的项数(由groupid定义)并需要按templateid过滤,但不考虑来自itemversion的多个版本

基本上我可以获得我需要的所有信息,并有查询从ItemVersion表中提取这些数据,但需要能够与Item表连接才能按模板过滤。

Item - PK = id + cultureid
id            cultureid     templateid      
1             1             5
1             2             5
2             1             4
2             2             4
2             3             4
3             1             5
4             1             7
4             1             11

ItemVersion (PK = id + cultureid + versionid)
id            cultureid     versionid     groupid 
1             1             1             11
1             2             2             11 
1             2             3             11 
1             2             4             11 
2             1             5             6
2             2             6             6
2             3             7             6
3             1             8             8
4             1             9             9
5             1             10            11

用于提取数据的SQL,但未正确聚合以删除多个版本

SELECT ItemVersion.groupid COUNT(ItemVersion.id) as VersionCount 
    FROM itemVersion iv JOIN ITEM i ON i.id = iv.cultureid AND iv.CultureId = i.CultureId 
        WHERE i.TemplateId != 11
            GROUP BY iv.groupid
                ORDER BY VersionCount desc

示例输出:

6      3
8      1
9      1 
11     1

更新 - 这就是诀窍: 感谢Branko指出我正确的方向

select ccv.WorkgroupID, COUNT(*) AS ArticleCount FROM ItemVersion ccv 
      JOIN Item cc ON
            CCV.Id = cc.Id AND CCV.CultureId = CC.CultureId

      WHERE 
      CCV.versionid in ( --Use latest version only for counts
                  select (MAX(ccv.versionid)) 
                        from ItemVersion ccv 
                              group by ccv.Id, ccv.CultureId
            )
      GROUP BY ccv.GroupId
      ORDER BY ArticleCount DESC

1 个答案:

答案 0 :(得分:1)

所以你想要计算每组项目的最新版本(并完全跳过非最新版本)?

如果是这样,以下查询应该完成这项工作:

SELECT groupid, COUNT(*)
FROM ItemVersion IV1
WHERE
    versionid = (
        SELECT MAX(versionid)
        FROM ItemVersion IV2
        WHERE IV1.id = IV2.id AND IV1.cultureid = IV2.cultureid
    )
GROUP BY groupid

如果您需要根据Item的其他条件进行过滤,则可以轻松将其加入查询中。例如:

SELECT groupid, COUNT(*)
FROM ItemVersion IV1 JOIN Item I ON IV1.id = I.id AND IV1.cultureid = I.cultureid
WHERE
    I.templateid <> 11
    AND versionid = (
        SELECT MAX(versionid)
        FROM ItemVersion IV2
        WHERE IV1.id = IV2.id AND IV1.cultureid = IV2.cultureid
    )
GROUP BY groupid