2

我有一个客户表:

id   name
1    customer1
2    customer2
3    customer3

和一个事务表:

id   customer   amount   type
1    1          10       type1
2    1          15       type1
3    1          15       type2
4    2          60       type2
5    3          23       type1

我希望我的查询返回的是下表

name        type1    type2
customer1   2        1
customer2   0        1
customer3   1        0

这表明 customer1 进行了 type1 的两次交易和 type2 的 1 次交易,依此类推。

是否有可用于获取此结果的查询,还是必须使用程序代码。

4

3 回答 3

2

你可以试试

select c.id as customer_id
   , c.name as customer_name
   , sum(case when t.`type` = 'type1' then 1 else 0 end) as count_of_type1
   , sum(case when t.`type` = 'type2' then 1 else 0 end) as count_of_type2
from customer c
   left join `transaction` t
   on c.id = t.customer
group by c.id, c.name

此查询只需要在连接上迭代一次。

于 2009-09-23T10:47:41.607 回答
1
SELECT  name, 
        (
        SELECT  COUNT(*)
        FROM    transaction t
        WHERE   t.customer = c.id
                AND t.type = 'type1'
        ) AS type1,
        (
        SELECT  COUNT(*)
        FROM    transaction t
        WHERE   t.customer = c.id
                AND t.type = 'type2'
        ) AS type2
FROM    customer c

要将WHERE条件应用于这些列,请使用:

SELECT  name
FROM    (
        SELECT  name, 
                (
                SELECT  COUNT(*)
                FROM    transaction t
                WHERE   t.customer = c.id
                        AND t.type = 'type1'
                ) AS type1,
                (
                SELECT  COUNT(*)
                FROM    transaction t
                WHERE   t.customer = c.id
                        AND t.type = 'type2'
                ) AS type2
        FROM    customer c
        ) q
WHERE   type1 > 3
于 2009-09-23T10:29:34.983 回答
1

德克打败了我;)

类似,但也可以在 mysql 4.1 中使用。

Select c.name,
sum(if(type == 1,1,0)) as `type_1_total`,
sum(if(type == 2,1,0)) as `type_2_total`,
from 
customer c
join transaction t on (c.id = t.customer)
;
于 2009-09-23T10:50:41.850 回答