更新时间:2016-05-14 09:33:24浏览次数:1+次
create table Employees
(
EmpID int NOT NULL,
EmpName char(10) NOT NULL
);
create table Orders
(
EmpID int NOT NULL,
SeasonNbr char(10) NOT NULL,
Sales money DEFAULT 0 NOT NULL
);
然后,我们在里面插入数据:insert into Employees values
(1,'Grace'),
(2,'Ken'),
(3,'Tom');
insert into Orders values
(1,'Season 1',100),
(1,'Season 2',100),
(1,'Season 3',120),
(1,'Season 4',130),
(2,'Season 1',200),
(2,'Season 2',300),
(2,'Season 3',150);
Employees表中存放着雇员的信息,Orders表存放和雇员的季度销售数据。对于数据存储设计而言,Orders的结构设计便于数据存取。不过,当我们需要进行数据比对的时候,我们更习惯于下面的表的设计结构:select Employees.EmpID, Employees.EmpName,
MAX(CASE
WHEN Orders.SeasonNbr='Season 1' THEN Orders.Sales
ELSE NULL
END) AS Season1,--AS关键字表示重命名
MAX(CASE
WHEN Orders.SeasonNbr='Season 2' THEN Orders.Sales
ELSE NULL
END) AS Season2,
MAX(CASE
WHEN Orders.SeasonNbr='Season 3' THEN Orders.Sales
ELSE NULL
END) AS Season3,
MAX(CASE
WHEN Orders.SeasonNbr='Season 4' THEN Orders.Sales
ELSE NULL
END) AS Season4
from Employees LEFT OUTER JOIN Orders
ON Employees.EmpID=Orders.EmpID
group by Employees.EmpID,Employees.EmpName;
正如所见的,左外部联接保留了LEFT OUTER JOIN关键字的左边表的整体数据,然后根据联接的匹配条件来选择性的添加该关键字的右边表中的数据。相关资讯