5

我有两个查询我想组合成一个输出,我不能使用 UNION 因为它们有不同数量的列。

该表的所有ref字段id refid cellid cat都包含整数

查询 1:查找每个唯一的总行数cellid

SELECT cellid, COUNT(*) totalcount, cat FROM rel GROUP BY cellid

cat查询 2:查找每个唯一的模式(最常见的值)cellid

SELECT cellid, cat
FROM rel t
GROUP BY cellid, cat
HAVING cat = (
SELECT cat
FROM rel
WHERE cellid = t.cellid
GROUP BY cat
ORDER BY COUNT(*) DESC, cat
LIMIT 1
)

举一个我正在尝试做的例子,我想查询我的表

id | refid | cellid | cat
1  | 1     |  1     | 1
2  | 2     |  2     | 2
3  | 3     |  3     | 4
4  | 1     |  1     | 2
5  | 2     |  1     | 2
6  | 3     |  1     | 3
7  | 1     |  2     | 2
8  | 1     |  1     | 2

并返回

cellid | no_of_rows | Mode_of_cat
 1     |  5         |  2
 2     |  2         |  2
 3     |  1         |  4
4

2 回答 2

10

这里最简单的解决方案就是编写一个查询来加入您已经拥有的两个结果集。您可以将查询结果存储在 tmp 表中,并像这样连接临时表:

SELECT tmp1.cellid, tmp1.rows, tmp2.mode_cat FROM
(
    SELECT cellid, COUNT(*) AS rows
    FROM rel
    GROUP BY cellid
)tmp1
LEFT JOIN
(
    SELECT cellid, cat AS mode_cat
    FROM rel t
    GROUP BY cellid, cat
    HAVING cat = (
        SELECT cat
        FROM rel
        WHERE cellid = t.cellid
        GROUP BY cat
        ORDER BY COUNT(*) DESC, cat
        LIMIT 1
    )
)tmp2
ON tmp1.cellid = tmp2.cellid;
于 2012-10-24T16:56:54.320 回答
3

在第二个查询中,您可以更改

SELECT cellid, cat

SELECT cellid, 0 as totalcount, cat

使其与第一个查询中的列匹配。

于 2012-10-24T16:36:20.033 回答