我会这样做 - 它包括一个测试,通过测试,您可以制作表格和数据以帮助您了解它的工作原理;
我假设员工只有一个地址,但接受多次付款,虽然可能没有必要从您的示例中的员工表中加入,但它显示了员工与其他表之间的关系是如何工作的,这可能有助于你更好地理解关系模型。
--Make the Tables
CREATE TABLE dbo.Employee
(
EmployeeID BIGINT PRIMARY KEY NOT NULL,
Name VARCHAR(50),
DoB DATE,
StartDate DATE
)
CREATE TABLE dbo.Salary
(
SalaryID BIGINT PRIMARY KEY NOT NULL,
DatePaid DATE, -- I think you mean DatePaid and not DataPaid
AmountPaid MONEY,
EmployeeID BIGINT
)
CREATE TABLE dbo.Address
(
AddressID BIGINT PRIMARY KEY NOT NULL,
[Address] VARCHAR(max),
City VARCHAR(200),
EmployeeID BIGINT
)
-- Put in some Test Data
INSERT INTO dbo.Employee (EmployeeID,Name, DoB, StartDate)
VALUES (1,'Bill Gates','19551028','20121014'),
(2,'Larry Ellison','19440817','20140101')
INSERT INTO dbo.Address (AddressID,[Address], City, EmployeeID)
VALUES (1,'15 Microsoft House','New York',1),
(2,'23 Oracle Flats','London',2)
INSERT INTO dbo.Salary(SalaryID, DatePaid, AmountPaid, EmployeeID)
VALUES (1,Getdate(),5000.53,1),
(2,'20140201',10000.23,2),
(3,'20140301',10000.23,2)
-- Queries;
--Count the number of employees that live in the city of London.
SELECT COUNT(Distinct E.EmployeeID) as Count_London
FROM dbo.Employee E
INNER JOIN dbo.[Address] A
ON E.EmployeeID = A.EmployeeID
WHERE A.City = 'London'
-- Result = 1
-- 2. Add up the 'AmountPaid' values for all employees from the city of London
--Total Amount
SELECT Sum(S.AmountPaid) as TotalPaid
FROM dbo.Employee E
INNER JOIN dbo.[Address] A
ON E.EmployeeID = A.EmployeeID
LEFT JOIN dbo.Salary S
ON E.EmployeeID = S.EmployeeID
WHERE A.City = 'London'
-- Result = 20000.46 (2 x 10000.23)
--split by employee;
SELECT E.EmployeeID,E.Name,Sum(S.AmountPaid) as TotalPaid
FROM dbo.Employee E
INNER JOIN dbo.[Address] A
ON E.EmployeeID = A.EmployeeID
LEFT JOIN dbo.Salary S
ON E.EmployeeID = S.EmployeeID
WHERE A.City = 'London'
GROUP BY E.EmployeeID, E.Name
--3. Display data for all employees that started in 2012
SELECT *
FROM dbo.Employee E
INNER JOIN dbo.[Address] A
ON E.EmployeeID = A.EmployeeID
LEFT JOIN dbo.Salary S
ON E.EmployeeID = S.EmployeeID
WHERE StartDate >= '20120101' AND StartDate < '20130101'
-- result = all bill gates fields
-- 4. Delete all records where the employee 'Name' field is empty/null.
DELETE FROM dbo.Employee WHERE EmployeeID IS NULL
你可能想要删除其中雇员是从所有表空,如果有可能在那里
你在做什么错吗?你为什么要问?你得到错误的结果? – 2014-11-14 15:11:36
首先,我们是处理sql-server还是mysql?你不能使用两个标签 - 选择一个。其次,我建议查找连接作为下一步 - 在伦敦查询中,您需要为您的薪水需要。此外,您的表结构表明一名员工可能拥有多个与其关联的地址。在该查询中使用COUNT(DISTINCT EmployeeID)而不是COUNT(城市)以获得更准确的结果。 – 2014-11-14 15:17:52