内部连接两个组合列的值

时间:2014-01-23 18:21:10

标签: sql-server tsql

我需要在两个组合列上进行内连接。

SELECT 
    [FullName], [Email], [Phone], [Goal], [TimeOfLead], [Location], [IPAddress] 
FROM 
    [Leads] 
INNER JOIN
    Clinics on [Clinics.City] + ', ' + [Clinics.State] as Location = Leads.Location 
WHERE
    Leads.Location = Clinics.Location

Leads Location将始终与city表格中的stateclinics相同。

如果我没有充分解释这个问题,请告诉我,我会修改这个问题。

1 个答案:

答案 0 :(得分:2)

这应该这样做。您不再需要WHERE子句,因为您正在INNER JOIN本身建立连接。

SELECT DISTINCT
    L.[FullName], L.[Email], L.[Phone], L.[Goal], L.[TimeOfLead], L.[Location], L.[IPAddress] 
FROM 
    [Leads] L
INNER JOIN
    Clinics C on L.Location = C.City + ', ' + C.State

这是一个SQL小提琴,包含一些示例数据和工作查询。 http://sqlfiddle.com/#!3/f53eb/2

创建表格,广告样本数据

CREATE TABLE Leads
( 
  FullName NVARCHAR(50) NULL,
  Email NVARCHAR(50) NOT NULL, 
  Phone NVARCHAR(20) NULL, 
  Goal NVARCHAR(50) NULL, 
  TimeOfLead NVARCHAR(50) NULL,
  Location NVARCHAR(50) NOT NULL, 
  IPAddress NVARCHAR(50) NULL  
);

CREATE TABLE Clinics
(
  ClinicName NVARCHAR(40) NOT NULL,
  City NVARCHAR(40) NOT NULL,
  State NVARCHAR(2) NOT NULL,
);

INSERT INTO Leads (FullName, Email, Location) VALUES
('John Duh', 'john@duh.com', 'San Francisco, CA'),
('Jane Dough', 'jane@dough.com', 'Austin, TX'),
('Bill Clinton', 'billy@presidents.com', 'Hope, AK');

INSERT INTO Clinics VALUES
('San Fran Clinic','San Francisco','CA'),
('Austin Clinic','Austin','TX'),
('Boise Clinic','Boise','ID'),
('Hope Clinic','Hope','AK');

执行查询。

SELECT DISTINCT 
    L.[FullName], L.[Email], L.[Phone], L.[Goal], L.[TimeOfLead], L.[Location], L.[IPAddress] 
FROM 
    [Leads] L
INNER JOIN
    Clinics C on L.Location = C.City + ', ' + C.State

<强>结果

FULLNAME    EMAIL   PHONE   GOAL    TIMEOFLEAD  LOCATION    IPADDRESS
John Duh    john@duh.com    (null)  (null)  (null)  San Francisco, CA   (null)
Jane Dough  jane@dough.com  (null)  (null)  (null)  Austin, TX  (null)
Bill Clinton    billy@presidents.com    (null)  (null)  (null)  Hope, AK    (null)