MySQL,左联接和计数条件

时间:2018-07-10 09:03:26

标签: mysql sql

我有休闲的SQL查询(伪查询):

SELECT 
    some columns [...]
    COUNT(clicks.id) AS clicks,
    COUNT(transactions.id) AS transactions 
FROM 
    campaign
LEFT JOIN   
    clicks ON clicks.key = campaign.key
LEFT JOIN (
    SELECT 
        id, key 
    FROM 
        transactions 
    GROUP BY 
        userkey 
    ) transactions ON clicks.key = transactions.key;
GROUP BY
    campaign.id

查询返回良好的结果。例如:

column | columns [..] | 34 | 10
column | columns [..] | 22 | 1
column | columns [..] | 34 | 17

因此,表点击中的记录包含交易或少量交易,或者没有交易。

山楂能否重新调整COUNT(transactions.id)= 0且COUNT(transactions.id)> 0的COUNT()次点击?例如:

column | columns [..] | 34 | 10 | 4 (count data from clicks table which have related transactions) | 30 (count data from clicks table which not have related transactions)
column | columns [..] | 22 | 1  | 6  | 16
column | columns [..] | 34 | 17 | 10 | 24

寻求帮助。

@UPDATE:

我解决了添加第二张桌子的问题。现在,我的SQL查询如下所示:

SELECT 
    some columns [...]
    COUNT(clicks.id) AS clicks,
    COUNT(transactions.id) AS transactions,
    COUNT(clicks_count.id) as witchout_transactions, 
    (COUNT(clicks.id) - COUNT(clicks_count.id)) as witch_transactions 
FROM 
    campaign
LEFT JOIN   
    clicks ON clicks.key = campaign.key
LEFT JOIN (
    SELECT 
        id, key 
    FROM 
        transactions 
    GROUP BY 
        userkey 
    ) transactions ON clicks.key = transactions.key
LEFT JOIN (
    SELECT 
        clicks.id, 
        COUNT(transactions.id) AS transactions 
    FROM 
        clicks 
    LEFT JOIN transactions ON clicks.key = transactions.key 
    GROUP BY clicks.id 
    HAVING transactions = 0
    ) clicks_count ON clicks_count.id = clicks.id 
GROUP BY
    campaign.id

2 个答案:

答案 0 :(得分:2)

如果我理解正确,则可以尝试使用git checkout branch2 git merge -Xours branch1 -m "syncing branch1" 表达式和CASE WHEN

因为您没有提供任何示例数据和预期结果,所以我只能提供伪查询。

COUNT

如果那对您没有帮助,您可以提供一些数据并期望结果,我将编辑我的答案。

答案 1 :(得分:1)

如何在clicks表中添加第二个联接

JOIN (
    SELECT id 
    FROM clicks
    LEFT JOIN transactions ON clicks.key = transactions.key AND transactions.id != 0) clicks2 ON clicks.id = clicks2.id

在select子句中,将其用于两列

SELECT 
    some columns [...]
    COUNT(clicks.id) AS clicks,
    COUNT(transactions.id) AS transactions
    COUNT(clicks2.id) as clicks_with
    clicks - clicks_with AS clicks_without