使用最大条目选择统计信息

时间:2014-11-11 11:33:31

标签: mysql sql


我有表clients

Id | utm_term | goal | region |
 1 |    a     |  aa  |  ccc   |
 2 |    b     |  aa  |  bbb   |
 3 |    c     |  bb  |  aaa   |
 4 |    b     |  cc  |  ccc   |

我需要选择count个客户端,utm_term包含最多条目,goal包含最大条目,region包含最大条目。
在输出中,它应该是:

Count | utm_term | goal | region |
  4   |    b     |  aa  |  ccc   |

我使用mysql,但理想情况下,我想要非平台解决方案。

1 个答案:

答案 0 :(得分:2)

您可以使用以下查询:

SELECT (
         SELECT COUNT(*)
           FROM clients
       ) AS Count,
       (
         SELECT utm_term
           FROM ( SELECT utm_term, COUNT(*) as count1
                    FROM clients
                GROUP BY utm_term
                ) AS s1
         ORDER BY count1 DESC
         LIMIT 1
       ) AS utm_term,
       (
         SELECT goal
           FROM ( SELECT goal, COUNT(*) as count1
                    FROM clients
                GROUP BY goal
                ) AS s2
         ORDER BY count1 DESC
         LIMIT 1
       ) AS goal,
       (
         SELECT region
           FROM ( SELECT region, COUNT(*) as count1
                    FROM clients
                GROUP BY region
                ) AS s3
         ORDER BY count1 DESC
         LIMIT 1
       ) AS goal