2

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 方式完成它。

4

1 回答 1

1

抱歉,我稍微更改了字段名称以使其更易于编码。以下查询将为您提供所需的内容:

SELECT 
  e1.HouseholdID,
  CASE WHEN p2.LastName =  p1.LastName THEN  p1.FirstName + ' & ' + p2.FirstName + ' ' + p2.LastName
       ELSE p1.FirstName + ' ' + p1.LastName + ' & ' + p2.FirstName + ' ' + p2.LastName END AS HouseholdName,
  p1.FirstName,
  p1.LastName,
  p2.FirstName as p2FirstName,
  p2.LastName as p2LastName
FROM 
 Person p1 
 INNER JOIN Entity e1 ON 
   p1.id = e1.PID
 LEFT JOIN Entity e2 
   ON e1.HouseholdID = e2.HouseholdID AND e1.id < e2.id
 LEFT JOIN Person p2
   ON e2.PID = p2.id
WHERE e2.ID IS NOT NULL
  AND NOT EXISTS 
    ( SELECT * FROM Entity e3 
      WHERE e1.HouseholdID = e3.HouseholdID
      AND NOT e3.id IN (e1.id, ISNULL(e2.id, 0))
    )

http://sqlfiddle.com/#!3/c8dd9/15

于 2013-01-13T00:11:22.357 回答