我在MySQL db中有一个表'C',结构如下:
Object1Id(int) - PK ,与表'A'有一对多的关系,
Object2Id(int) - PK ,与表'A'有一对多的关系,
OccuranceId(int) - FK 与表'B'有一对多的关系。
基本上,表'C'与表'A'有很多种关系,与表'B'有一对多的关系。
数据:
1, 3, 1
1, 3, 39
3, 1, 402
3, 1, 27
1, 3, 40
3, 1, 12
我尝试使用查询对记录进行分组:
SELECT CASE WHEN least(Object1Id, Object2Id) = Object1Id THEN Object1Id ELSE Object2Id END AS Object1Id,
CASE WHEN Greatest(Object1Id, Object2Id) = Object2Id THEN Object2Id ELSE Object1Id END AS Object2Id,
count(OccuranceId) AS OccuranceCount
FROM 'C'
GROUP BY Object1Id, Object2Id
我从查询中得到的结果是:
1,3,3 - 对于object1Id = 1和Object2Id = 3
1,3,3 - Object1Id = 3且Object2Id = 1
我希望结果总结为:1,3,6
如何产生预期效果?
感谢。
答案 0 :(得分:0)
首先,我将查询简化为
SELECT least(Object1Id, Object2Id) AS Object1Id,
Greatest(Object1Id, Object2Id) AS Object2Id,
count(OccuranceId) AS OccuranceCount
FROM C
GROUP BY Object1Id, Object2Id
您的查询不起作用,因为您有列object1id
和object2id
,并将这些名称重用于结果列least()
和greatest()
。但是group by
子句按表列分组而不是结果列。将结果列重命名为其他名称时,它可以按预期工作
SELECT least(Object1Id, Object2Id) AS least_val,
Greatest(Object1Id, Object2Id) AS greatest_val,
count(OccuranceId) AS OccuranceCount
FROM C
GROUP BY least_val, greatest_val
SQL Fiddle进行测试
答案 1 :(得分:0)
是!
SELECT Object1Id, Object2Id, sum(OccuranceCount)
FROM (
__ YOUR SELECT __
) foo