如何通过连接将表中一列关联至另一表多列?附两表新增列需求
Alright, let's tackle this problem. It looks like you need to join the Customer table with the Age table on CustomerID, plus add a column (I'll assume it's HasAge since the name was cut off) to flag whether each customer has a corresponding age entry. Here's a clean SQL Server solution tailored to your table variables:
Full SQL Implementation
-- Define and populate the Customer table variable declare @customer table (CustomerID INT, CustomerName VARCHAR(10)) INSERT INTO @customer VALUES (1, 'Shane'), (2, 'Daniel'), (3, 'Karim'), (4, 'Eric'), (5, 'Zoe'), (6, 'Jack') -- Define and populate the Age table variable declare @age table (CustomerID INT, Age INT) INSERT INTO @age VALUES (1, 20), (2, 19), (3, 12), (6, 30) -- Join tables and add the HasAge flag column SELECT c.CustomerID, c.CustomerName, a.Age, -- Flag: 1 = has age record, 0 = no age record CASE WHEN a.CustomerID IS NOT NULL THEN 1 ELSE 0 END AS HasAge FROM @customer c LEFT JOIN @age a ON c.CustomerID = a.CustomerID
Key Details Explained
LEFT JOIN: This ensures we keep every customer from theCustomertable, even if they don't have an entry in theAgetable (like Eric and Zoe in your sample data). If you only wanted customers with existing age records, you'd useINNER JOINinstead.CASEStatement: This generates theHasAgecolumn by checking if the joinedAgetable has a matching record. We usea.CustomerID IS NOT NULLas the check becauseLEFT JOINreturnsNULLfor columns from theAgetable when there's no match.- Alternative Simplified Syntax: If you're using SQL Server 2012 or later, you can use
IIF()as a shorter replacement for theCASEstatement:
This does exactly the same thing, just with less code.IIF(a.CustomerID IS NOT NULL, 1, 0) AS HasAge
Sample Output
Running the query will give you this result:
| CustomerID | CustomerName | Age | HasAge |
|---|---|---|---|
| 1 | Shane | 20 | 1 |
| 2 | Daniel | 19 | 1 |
| 3 | Karim | 12 | 1 |
| 4 | Eric | NULL | 0 |
| 5 | Zoe | NULL | 0 |
| 6 | Jack | 30 | 1 |
内容的提问来源于stack exchange,提问作者Akira
相关产品推荐
相关产品推荐

