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

求SQL语句:筛选同时拥有Noida和Chennai地址的客户全量行

How to Get All Rows for Customers with Both Noida and Chennai Addresses

Hey there, let's tackle this SQL problem together!

First, let's lay out the sample data we're working with:

Sample Input

CustomerAdd SeqCityPhone
Test11Delhi1231
Test12Noida2334
Test21Bengaluru3333
Test22Noida3333
Test23Chennai5565
Test32Chennai5565
Test41Noida3333
Test42Chennai5565
Test51Chennai5565

What We Need

We want to fetch all Noida/Chennai rows for customers who have addresses in both cities—matching the expected output you shared.

The Solution Query

Here's a clean, efficient way to do this using a subquery to first identify qualifying customers, then pull their relevant rows:

SELECT t.*
FROM your_table_name t
INNER JOIN (
    -- Step 1: Find customers who have both Noida and Chennai addresses
    SELECT Customer
    FROM your_table_name
    WHERE City IN ('Noida', 'Chennai')
    GROUP BY Customer
    HAVING COUNT(DISTINCT City) = 2
) qualifying_customers 
    ON t.Customer = qualifying_customers.Customer
-- Step 2: Filter to only the Noida/Chennai rows for these customers
WHERE t.City IN ('Noida', 'Chennai');

How It Works

  1. Subquery: The inner query narrows down to customers who have entries for both cities. We filter rows to only Noida/Chennai first, group by customer, and use HAVING COUNT(DISTINCT City) = 2 to ensure they have both (this avoids counting duplicates if a customer has multiple entries for the same city).
  2. Join & Filter: We join this list of qualifying customers back to the original table, then add a final filter to only keep the Noida and Chennai rows. If you wanted all rows for these customers—including Test2's Bengaluru entry—just remove the last WHERE clause.

Expected Output

Running this query will give you exactly what you're looking for:

CustomerAdd SeqCityPhone
Test22Noida3333
Test23Chennai5565
Test41Noida3333
Test42Chennai5565

内容的提问来源于stack exchange,提问作者Newbiee SQL

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 13:12:32