我在这里有两个表:{1}}和Customer
一对一的关系。换句话说,Company
表具有PK Company
列,该列是引用Customer的PK customerid
的外键。这意味着,如果id
表中有记录,那么相应的客户就是公司。
以下是简化可视化图表:
现在,当您想要了解每个字母(代表客户名称或公司名称)两个表中有多少客户和公司时,您可以执行以下查询:
Company
然后你得到以下结果集:
但是,我的结果集中仍然需要一个生成的列(例如列'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
<...>
答案 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;