Entity
我的目标是为由 2 人组成的所有家庭计算并在表格上设置一个 HouseholdName 字段。我正在使用 SQL Server 2012,我必须使用的架构是:
CREATE TABLE Entity
(
EID INT, --PK
PID INT, --FK to Person.[Person ID]
HouseholdID VARCHAR(50),
HouseholdName VARCHAR(300)
);
CREATE TABLE Person
(
[Person ID] INT,
FirstName VARCHAR(30),
LastName VARCHAR(30)
);
INSERT INTO Entity VALUES (1,1,'HH1',NULL);
INSERT INTO Entity VALUES (2,2,'HH1',NULL);
INSERT INTO Entity VALUES (3,3,'HH2',NULL);
INSERT INTO Entity VALUES (4,4,'HH2',NULL);
INSERT INTO Entity VALUES (5,5,'HH3',NULL);
INSERT INTO Person VALUES (1,'Jane', 'Doe');
INSERT INTO Person VALUES (2,'Joe', 'Doe');
INSERT INTO Person VALUES (3,'Sara', 'Dillin');
INSERT INTO Person VALUES (4,'Bill', 'Smith');
INSERT INTO Person VALUES (5,'Ted', 'Loner');
计算家喻户晓的逻辑是这样的:如果两个姓氏相同,例如 HouseholdID HH1
,家喻户晓的名字应该是“Jane & Joe Doe”。如果姓氏不同,例如HH2
应该采用“Sara Dillin & Bill Smith”格式
我可以识别这些人并让他们按如下顺序排列:
SELECT FirstName,LastName,HouseholdID
FROM Entity e
JOIN Person p ON p.[Person ID]=e.[PID]
WHERE HouseholdID IN --HHs of 2 people
(
SELECT DISTINCT HouseholdID
FROM Entity e
JOIN Person p ON p.[Person ID]=e.[PID]
GROUP BY HouseholdID HAVING COUNT(*)=2
)
ORDER BY HouseholdID
但我已经过去了。从像 C# 这样的过程语言我知道如何解决这个问题,但它很慢。我希望能够以更快的 SQL 方式完成它。