使用GROUP BY时的复杂条件列

时间:2018-05-26 07:59:59

标签: mysql sql

我在这里有两个表:{1}}和Customer一对一的关系。换句话说,Company表具有PK Company列,该列是引用Customer的PK customerid的外键。这意味着,如果id表中有记录,那么相应的客户就是公司。

以下是简化可视化图表:

enter image description here

现在,当您想要了解每个字母(代表客户名称或公司名称)两个表中有多少客户和公司时,您可以执行以下查询:

Company

然后你得到以下结果集:

enter image description here

但是,我的结果集中仍然需要一个生成的列(例如列'type`),我可以看到是否只有客户代表相应的字母或公司,或两者兼而有。

这意味着:我需要这样的结果集:

SELECT LEFT(u.name, 1) AS letter, count(*) AS count FROM 
    (
        SELECT name,
            CASE
                WHEN (SELECT customerid FROM company WHERE company.customerid = id) THEN "Company"
                ELSE "Customer"
            END
            AS origin
        FROM customer
        UNION ALL
        SELECT companyname AS name, 'Company' AS origin FROM company
    ) AS u
GROUP BY letter
ORDER BY letter

是否可以通过实施条件列来实现?我已经尝试了很多不同的东西;它每次都失败了。

仅限于案例

以防您需要这个简化的SQL种子:

letter | count | type
--------------------------
A        1       Companies
B        3       Both
C        2       Customers
<...>

1 个答案:

答案 0 :(得分:1)

您可以在计算的origin列上使用条件聚合来进行检查:

SELECT
    LEFT(u.name, 1) AS letter,
    COUNT(*) AS count,
    CASE WHEN COUNT(CASE WHEN origin = 'Company' THEN 1 END) > 0 AND
              COUNT(CASE WHEN origin = 'Customer' THEN 1 END) > 0
         THEN 'Both'
         WHEN COUNT(CASE WHEN origin = 'Company' THEN 1 END) > 0
         THEN 'Companies'
         WHEN COUNT(CASE WHEN origin = 'Customer' THEN 1 END) > 0
         THEN 'Customers' END AS type
FROM 
(
    SELECT name, 'Customer' AS origin FROM customer
    UNION ALL
    SELECT companyname, 'Company'     FROM company
) t
GROUP BY letter
ORDER BY letter;