在一个查询中计算带有group by的多个列

时间:2012-10-02 15:12:34

标签: sql database count group-by

我计算来自多个列的值,如下所示:

SELECT COUNT(column1),column1 FROM table GROUP BY column1
SELECT COUNT(column2),column2 FROM table GROUP BY column2
SELECT COUNT(column3),column3 FROM table GROUP BY column3

例如,对于column1数组(attr1 => 2000,attr2 => 3000 ...)返回(每列具有特定值和少量值)。问题是我的应用程序中的“表”可以是带有一些连接和where子句的查询,可能需要0.1秒。通过做所有计数,每次再次计算“表”,这是不必要的。有没有办法用一个查询获取我想要的结果,或“缓存”生成表的查询?否则我相信非规范化将是这里唯一的解决方案。我想要与上述查询相同的结果。我正在使用mysql-myisam。

6 个答案:

答案 0 :(得分:40)

如果不了解数据的上下文/结构,很难知道如何帮助您,但我相信这可能会对您有所帮助:

SELECT 
     SUM(CASE WHEN column1 IS NOT NULL THEN 1 ELSE 0 END) AS column1_count
    ,SUM(CASE WHEN column2 IS NOT NULL THEN 1 ELSE 0 END) AS column2_count
    ,SUM(CASE WHEN column3 IS NOT NULL THEN 1 ELSE 0 END) AS column3_count
FROM table

答案 1 :(得分:8)

一种解决方案是将其包装在子查询中

SELECT *
FROM
(
    SELECT COUNT(column1),column1 FROM table GROUP BY column1
    UNION ALL
    SELECT COUNT(column2),column2 FROM table GROUP BY column2
    UNION ALL
    SELECT COUNT(column3),column3 FROM table GROUP BY column3
) s

答案 2 :(得分:3)

select tab1.name,
count(distinct tab2.id) as tab2_record_count
count(distinct tab3.id) as tab3_record_count
count(distinct tab4.id) as tab4_record_count
from tab1
left join tab2 on tab2.tab1_id = tab1.id
left join tab3 on tab3.tab1_id = tab1.id
left join tab4 on tab4.tab1_id = tab1.id

答案 3 :(得分:1)

您没有说明您使用的是哪个数据库服务器,但如果临时表可用,则可能是最佳方法。

// table is a temp table
select ... into #table ....
SELECT COUNT(column1),column1 FROM #table GROUP BY column1  
SELECT COUNT(column2),column2 FROM #table GROUP BY column2  
SELECT COUNT(column3),column3 FROM #table GROUP BY column3  
// drop may not be required
drop table #table

答案 4 :(得分:0)

    SELECT SUM(Output.count),Output.attr 
FROM
(
    SELECT COUNT(column1  ) AS count,column1 AS attr FROM tab1 GROUP BY column1 
    UNION ALL
    SELECT COUNT(column2) AS count,column2 AS attr FROM tab1 GROUP BY column2
    UNION ALL
    SELECT COUNT(column3) AS count,column3 AS attr FROM tab1 GROUP BY column3) AS Output

    GROUP BY attr 

答案 5 :(得分:0)

从[table_name] GROUP BY col1,col2;中选择COUNT(col1或col2);