我想知道一列值在结果中显示多少次,并将其包含在每一行结果的一列中。如何在不对派生表重复两次子查询的情况下实现此目的?如果我在COUNT子查询中用“ t”替换(可派生表),则表示该表不存在。
SELECT
col1,
col2,
col3,
(SELECT COUNT(*) FROM (derivedtable) WHERE t.col1=col1)
FROM (derivedtable) AS t
最佳答案
您可以只使用group by
吗?
SELECT col1, col2, col3, COUNT(*)
FROM (derivedtable) AS t
GROUP BY col1;
这将返回任意值
col2
和col3
。您可以使用group_concat()
获取完整列表:SELECT col1, group_concat(col2) as col2s, group_concat(col3) as col3s, COUNT(*)
FROM (derivedtable) AS t
GROUP BY col1;
编辑:
如果您确实想在不重复派生表的情况下执行此操作,则可以使用变量:
SELECT col1, col2, col3,
@col1cnta := if(@col1a = col1, @col1cnta, col1cnt) as col1cnt,
@col1a := col
FROM (SELECT col1, col2, col3,
@col1cnt := if(@col1 = col1, 0, @col1cnt) + COUNT(*) as col1cnt,
@col1 := col1
FROM (derivedtable) t cross join
(select @col1 := '', @col1cnt := 0) const
GROUP BY col1
) t cross join
(select @col1a := '', @col1cnta := 0) const
ORDER BY col1, col1cnt desc;
这里的想法是对三列的每个组合进行子计数。然后,将结果按
col1
排序,但计数顺序相反,并在给定col1
的所有行中复制最大值。关于mysql - mysql-如何不重复派生表的子查询,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22359963/