如何同时查询和统计和计数?

时间:2018-02-07 06:29:22

标签: mysql h2

SELECT * FROM UserTable limit 100 ORDER BY userID ASC offset 0 ROWS;
SELECT COUNT(*) FROM UserTable;
SELECT COUNT(DISTINCT email) FROM UserTable;

如何将它们全部合并到一个查询中?

预期输出应该类似于

totalCount    distinctCount    userID    email ...
100000        1000             1         qwerty@qwerty.com
100000        1000             2         qwerty@qwerty.com
100000        1000             3         abc.abc.com
...

4 个答案:

答案 0 :(得分:1)

您可以在count子查询

上使用交叉连接
  SELECT t.totalCount, t.distinctCount, UserTable.* 
  FROM UserTable 
  cross join (
    SELECT COUNT(*)  totalCount, COUNT(DISTINCT email) as distinctCount
    FROM UserTable
  ) t 
  ORDER BY userID ASC limit 100 

答案 1 :(得分:1)

你在这里:

    select 
(select count(*) from UserTable a) as count,
(select count(DISTINCT quarter) from UserTable b) as distinctCount,
c.* from UserTable as c order by userID ASC limit 100;

答案 2 :(得分:0)

您正在寻找一个小组:

尝试以下查询:

SELECT * FROM UserTable limit 100 ORDER BY userID ASC offset 0 ROWS GROUP BY email

答案 3 :(得分:0)

你可以使用子查询加入MySQL来实现它:

SELECT UserTable.*, tc.totalCount, dc.distinctCount
FROM UserTable 
JOIN (
    SELECT COUNT(*) as totalCount
    FROM UserTable
) tc
JOIN (
    SELECT COUNT(DISTINCT email) as distinctCunt
    FROM UserTable
) dc
ORDER BY userID ASC 
LIMIT 100