![](/img/trans.png)
[英]MySQL Inner Join two tables on the maximum values of the second table
[英]MYSQL: How to join two tables using Inner join and then calculatin the total number from the second table for the following examples
我堅持以下要求,我發現很難破解它的查詢。
考慮具有以下字段的表客戶
id signup_date first_payment_date
10 2015-03-20 null
11 2015-03-20 null
12 2015-03-20 null
13 2015-03-20 null
14 2015-05-23 null
15 2015-05-23 null
考慮另一個表transaction_history
id product_name
10 vod trial
10 vod trial
11 vod trial
12 vod trial
12 vod
13 vod trial
14 vod trial
15 vod trial
15 vod trial
我需要從customer表中選擇id
,並根據signup_date
在transaction_history表中signup_date
, first_payment_date
為null
。
現在我需要檢查transaction_history中是否存在此id
,並檢查他是否至少有1個帶有product_name = "vod trial"
條目。 如果他有,那么他就是我想要的結果。
最后,我需要計算來自transaction_history的id的總數,其中至少有一行product_name="vod_trial"
,這應該是在customer表的signup_date
中提到的日期。
我用以下方式編寫了一個查詢:
SELECT
ts.guid,
cs.signup_date,
(SELECT
COUNT(ts2.guid)
FROM
transaction_history ts2
WHERE
cs.guid = ts2.guid
AND ts2.product_name = "vod trial"
HAVING COUNT(ts2.guid) = 1) AS count_ts_guid
FROM
customer AS cs,
transaction_history AS ts
WHERE
cs.guid = ts.guid
AND cs.first_payment_date IS NULL;
但在上面的查詢中,我無法計算signup_datewise的總計數。
如果有人可以幫助我,那會很棒。
樣本結果:
date new trials
2015-03-20 2
2015-05-23 1
我不確定我完全理解。 您希望沒有first_payment_date的客戶在交易表中有試用條目嗎?
select *
from customer
where first_payment_date is null
and id in (select id from transaction_history where product_name = 'vod trial');
好的,從您上次的評論來看,您也希望客戶在交易表中沒有試用條目。 並且您希望使用他們的試用交易計數來顯示它們。 所以:
select signup_date,
(
select count(*)
from transaction_history th
where th.product_name = 'vod trial'
and th.id = c.id
)
from customer c
where first_payment_date is null;
如果您甚至想按日期分組,那么匯總:
select signup_date,
sum((
select count(*)
from transaction_history th
where th.product_name = 'vod trial'
and th.id = c.id
))
from customer c
where first_payment_date is null
group by signup_date;
接下來嘗試:加入所有客戶和交易,例如只獲得交易表中的客戶。 然后聚合。
select c.signup_date, count(*)
from customer c
join transaction_history th on th.id = c.id and th.product_name = 'vod trial'
where c.first_payment_date is null
group by c.signup_date;
或者你想要這個:
select c.signup_date, count(case when th.product_name = 'vod trial' then 1 end)
from customer c
join transaction_history th on th.id = c.id
where c.first_payment_date is null
group by c.signup_date;
我最好把它作為一個單獨的答案。 您希望找到在transaction_history中只有一個條目且該條目必須為“vod trial”的客戶。 因此,請閱讀交易表,按客戶ID和計數分組。 用HAVING檢查你的標准。 然后將找到的ID與客戶表和按日期分組。
select c.signup_date, count(*)
from customer c
join
(
select id
from transaction_history
group by id
having count(*) = 1
and min(product_name) = 'vod trial'
) t on t.id = c.id
group by c.signup_date;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.