MySQL统计所有和计数明显超过2列相同的查询

时间:2015-02-04 01:14:55

标签: mysql sql

目前,我有以下查询来计算购买特定商品的不同(客户用户名和商店ID)的行数。如何计算同一查询中item_id = 3的总(所有)行数?

SELECT count(*)
FROM (
SELECT DISTINCT customer_username, store_id
FROM transactions
WHERE item_id = 3)

3 个答案:

答案 0 :(得分:1)

您可以尝试这样的事情:

SELECT COUNT(*), SUM(customer_cnt) FROM (
    SELECT customer_username, store_id, COUNT(*) AS customer_cnt
      FROM transactions
     WHERE item_id = 3
     GROUP BY customer_username, store_id
) t;

答案 1 :(得分:0)

尝试在查询中删除DISTINCT:

SELECT count(*)
FROM (
SELECT customer_username, store_id
FROM transactions
WHERE item_id = 3)

答案 2 :(得分:0)

另一种方式是2个内联视图的cross join

select x.distinct_rows, y.total_rows
  from (select count(distinct concat(user_name, store_id)) as distinct_rows
          from transactions
         where item_id = 3) x
 cross join (select count(*) as total_rows
               from transactions
              where item_id = 3) y