arrayA[3]==null?"":arrayA[3];
goods
id name rent_price
1 Toyota 400000
2 Honda 500000
3 Mazda 600000
4 Suzuki 700000
5 KIA 800000
customers
id name
1 Ali
2 Budi
3 Candra
4 Doni
5 Eka
history_transactions
id customer_id date
1 1 2016-03-01 15:00:00
2 4 2016-03-02 15:00:00
3 4 2016-03-02 17:00:00
4 2 2016-03-03 09:00:00
5 4 2016-03-05 10:00:00
6 1 2016-04-06 10:00:00
7 5 2016-05-07 10:00:00
8 2 2016-06-08 10:00:00
9 1 2016-07-09 10:00:00
10 2 2016-08-10 10:00:00
我有很多数据 历史交易的165.000行 客户18.000行
我需要数天的客户为每个客户进行交易
history_rents
id history_transaction_id good_id
1 1 1
2 2 2
3 2 5
4 3 3
5 4 1
6 4 2
7 4 3
8 4 4
9 4 5
10 5 5
11 6 3
12 7 4
13 8 3
14 9 1
15 10 1
我需要计算每个客户租用的物品
customers
id name day_trans
1 Ali 3
2 Budi 3
3 Candra 0
4 Doni 2 (history_transaction_id 2 & 3 count as 1)
5 Eka 1
请帮助查询以及我应该为索引
指定哪个字段答案 0 :(得分:0)
如果您希望通过两个不同的查询来输出两个输出:
输出#1:
customers
id name day_trans
1 Ali 3
2 Budi 3
3 Candra 0
4 Doni 2 (history_transaction_id 2 & 3 count as 1)
5 Eka 1
查询#1:
SELECT
C.id,
C.name,
COUNT(DISTINCT DATE(HT.`date`)) AS day_trans
FROM customers C
INNER JOIN history_transactions HT
ON C.id = HT.customer_id
GROUP BY C.id
ORDER BY C.id;
输出#2:
customers
id name rent_count
1 Ali 3
2 Budi 7
3 Candra 0
4 Doni 4
5 Eka 1
查询#2:
SELECT
C.id,
C.name,
COALESCE(t.total,0) AS rent_count
FROM customers C
LEFT JOIN
(
SELECT
HT.customer_id,
COUNT(*) total
FROM history_rents HR
INNER JOIN history_transactions HT
ON HR.history_transaction_id = HT.id
GROUP BY HT.customer_id
) AS t
ON C.id = t.customer_id
ORDER BY C.id;
如果你想让他们通过一个:
SELECT
C.id,
C.name,
COALESCE(t.day_trans,0) AS day_trans
COALESCE(t.total_rent,0) AS rent_count
FROM customers C
LEFT JOIN
(
SELECT
HT.customer_id,
COUNT(DISTINCT DATE(HT.`date`)) AS day_trans,
COUNT(*) total_rent
FROM history_rents HR
INNER JOIN history_transactions HT
ON HR.history_transaction_id = HT.id
GROUP BY HT.customer_id
) AS t
ON C.id = t.customer_id
答案 1 :(得分:0)
您可以在同一个查询中执行这两项操作:
SELECT c.id, c.name, count(distinct date(ht.date)) as day_trans, count(*) as rent_count
FROM customers c
LEFT JOIN history_transactions ht on c.id=ht.customer_id
LEFT JOIN history_rents hr on ht.id=hr.history_transaction_id
GROUP by c.id