Sql组数据?结合?

时间:2014-07-21 16:24:37

标签: sql group-by

如果我输入

SELECT petid1, COUNT( * ) AS total FROM cdc_padchat WHERE petid1 !=0 GROUP BY petid1
ORDER BY total DESC

它将输出以下数据

enter image description here

如果我输入

SELECT petid2, COUNT( * ) AS total FROM cdc_padchat WHERE petid2 !=0 GROUP BY petid2
ORDER BY total DESC

它将输出以下数据

enter image description here

如何对结果进行分组? 例如petid1 = 1218总结果+ petid2 = 1218总结果= 20 + 9 = 29

2 个答案:

答案 0 :(得分:1)

加入生成的查询并合并总计。不确定您使用的数据库,但应该是这样的:

SELECT petid1, petid2, (a.total + b.total) as combinedtotal
FROM
    (SELECT petid1, COUNT( * ) AS total FROM cdc_padchat WHERE petid1 !=0 GROUP BY petid1) a
INNER JOIN
    (SELECT petid2, COUNT( * ) AS total FROM cdc_padchat WHERE petid2 !=0 GROUP BY petid2) b
ON a.petid1 = b.petid2
ORDER BY combinedtotal DESC

这只会返回那些匹配petid1和petid2的记录,所以在你的例子中,id的1240和995不会显示。如果要显示这些记录,请将连接更改为FULL JOIN。

答案 1 :(得分:0)

您已尝试合并两个输出。由于这些是两条独立的信息,因此您需要在问题中使用这两个查询。通过使用union all,您可以将它们合并到一个表中。

SELECT petid1 as petid, COUNT( * ) AS total FROM cdc_padchat WHERE petid1 !=0 GROUP BY petid1
Union all
SELECT petid2 as petid, COUNT( * ) AS total FROM cdc_padchat WHERE petid2 !=0 GROUP BY petid2

此查询的输出将是

petid | total
1218  | 20
9102  | 18
995   | 10
1238  | 9
1217  | 8
912   | 10
1218  | 9
1238  | 8
1240  | 6
1217  | 5

现在,为了组合petid,您需要将上述查询转换为子查询并将组移动到外部查询。

Select petid, count(*) as total
From(
    SELECT petid1 as petid FROM cdc_padchat WHERE petid1 !=0 
    Union all
    SELECT petid2 as petid FROM cdc_padchat WHERE petid2 !=0
)
GROUP BY petid
Order by total desc

这可以为您提供所需的信息。

相关问题