You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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:

  1. Inner Union Query: This combines two datasets:

    • All customers, labeled as Company if they have a matching record in the company table, otherwise Customer.
    • All company names, explicitly labeled as Company.
  2. 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 CASE statement maps these results to your desired type labels:
      • If both checks return 1 → Both.
      • If only the customer check returns 1 → Customers.
      • If only the company check returns 1 → Companies.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:04:32