table1
id key1 key2 key3 key4
1 112 222 333 null
2 112 222 333 null
3 134 222 333 444
4 134 000 333 444
5 178 212 312 412
table2
id
1
1
2
4
5
我想要对该表进行信息的统计:
1)查询table2,id去重;得到id=1、2、4、5;
2)利用id与table1关联,并根据key1、key2、key3、key4进行统计:id=1和id=2的几个key都一样,因此这几个key为一组,且出现次数为2
示例结果:
key1 key2 key3 key4 times
112 222 333 null 2
134 222 333 444 0
134 000 333 444 1
178 212 312 412 1
求教高手!
3 个解决方案
#1
SELECT a.`key1`,a.`key2`,a.`key3`,a.`key4`,COUNT(DISTINCT b.id) FROM tr1 a
LEFT JOIN tr2 b ON a.`id`=b.`id`
GROUP BY a.`key1`,a.`key2`,a.`key3`,a.`key4`
LEFT JOIN tr2 b ON a.`id`=b.`id`
GROUP BY a.`key1`,a.`key2`,a.`key3`,a.`key4`
#2
测试过,结果正确,谢谢版主!
#3
#1
SELECT a.`key1`,a.`key2`,a.`key3`,a.`key4`,COUNT(DISTINCT b.id) FROM tr1 a
LEFT JOIN tr2 b ON a.`id`=b.`id`
GROUP BY a.`key1`,a.`key2`,a.`key3`,a.`key4`
LEFT JOIN tr2 b ON a.`id`=b.`id`
GROUP BY a.`key1`,a.`key2`,a.`key3`,a.`key4`
#2
测试过,结果正确,谢谢版主!