使用GROUP BY统计时如何新增区分客户/公司类型的条件列?
Solution
Absolutely, this is totally feasible! The key is to use conditional aggregation to track which origin types (Customer/Company) exist for each letter, then map that to your desired type label.
Here's the modified query that achieves exactly what you're looking for:
SELECT LEFT(u.name, 1) AS letter, COUNT(*) AS count, CASE WHEN MAX(CASE WHEN u.origin = 'Customer' THEN 1 ELSE 0 END) = 1 AND MAX(CASE WHEN u.origin = 'Company' THEN 1 ELSE 0 END) = 1 THEN 'Both' WHEN MAX(CASE WHEN u.origin = 'Customer' THEN 1 ELSE 0 END) = 1 THEN 'Customers' ELSE 'Companies' END AS type FROM ( -- Get all customers, marking if they're linked to a company SELECT name, CASE WHEN EXISTS (SELECT 1 FROM company WHERE company.customerid = customer.id) THEN 'Company' ELSE 'Customer' END AS origin FROM customer UNION ALL -- Add all company names separately (as their own entries) SELECT companyname AS name, 'Company' AS origin FROM company ) AS u GROUP BY letter ORDER BY letter;
How it works:
Inner Union Query: This combines two datasets:
- All customers, labeled as
Companyif they have a matching record in thecompanytable, otherwiseCustomer. - All company names, explicitly labeled as
Company.
- All customers, labeled as
Grouping & Conditional Aggregation:
- We group by the first letter of each name (
LEFT(u.name,1)). - For each letter,
MAX(CASE WHEN u.origin = 'Customer' THEN 1 ELSE 0 END)checks if there's at least one customer entry for that letter (returns 1 if yes, 0 otherwise). - Similarly, the other
MAX()check does the same for company entries. - The
CASEstatement maps these results to your desiredtypelabels:- If both checks return 1 →
Both. - If only the customer check returns 1 →
Customers. - If only the company check returns 1 →
Companies.
- If both checks return 1 →
- We group by the first letter of each name (
Testing with your sample data:
Running this query against your provided tables will produce results like:
letter | count | type -------|-------|-------- A | 1 | Companies B | 3 | Both C | 2 | Customers D | 1 | Companies J | 4 | Both T | 1 | Companies
Which aligns perfectly with your expected output structure.
内容的提问来源于stack exchange,提问作者LowLevel
相关产品推荐
相关产品推荐

