我需要从查询中返回的是过去一年访问过的家庭户主及其所有亲属的名单。每个人都在Client表中,在查询时它连接到其他表。
问题是查询为每个唯一的DateVisited返回一组Family成员。我希望得到一组看起来像这样的结果(为了清楚起见,我省略了一些列):
Head of household Relative/child
---------------------------- ---------------------
John Smith - Katie Smith
John Smith Joe Smith
Tim Jones Mike Jones
Tim Jones Sally Jones
Kevin Barnett Corey Barnett
Kevin Barnett Cara Barnett
Kevin Barnett Austin Barnett
SELECT f.HeadOfHouseholdID,
CONCAT( c.lastname, ', ', c.firstname ) AS 'HName',
v.Datevisited, f.RelationshipID, c2.ClientID,
CONCAT( c2.lastname, ', ', c2.firstname ) AS 'Relative Name'
FROM client c
INNER JOIN clientfamily f ON c.ClientID = f.HeadOfHouseholdID
JOIN visits v ON c.clientid = v.clientID
JOIN client c2 ON c2.clientid = f.relativeID
WHERE v.datevisited BETWEEN CURDATE( ) - INTERVAL 1 YEAR AND CURDATE( )
![查询结果] [1]
答案 0 :(得分:0)
一位同事想通了:
SELECT f.HeadOfHouseholdID 'HOHID',
CONCAT( c.Lastname, ', ', c.FirstName ) AS 'Head of Household',
c.PhoneNumber AS 'HOH Phone',
f.RelativeID,
CONCAT( C2.Lastname, ', ', C2.FirstName ) AS 'Relative',
Relationship.Description AS 'Relation',
C2.PhoneNumber AS 'Relative Phone', C2.DOB,
(
(
DATE_FORMAT( NOW( ) , '%Y' ) - DATE_FORMAT( C2.DOB, '%Y' )
) -
( DATE_FORMAT( NOW( ) , '00-%m-%d' ) < DATE_FORMAT( C2.DOB, '00-%m-%d' ) )
) AS Age
FROM client c
INNER JOIN clientfamily f ON c.clientid = f.headofhouseholdid
JOIN (
SELECT ClientID, MAX( DateVisited ) AS 'DateVisited'
FROM Visits
GROUP BY ClientID
) v ON c.clientid = v.clientid
JOIN client c2 ON c2.clientid = f.relativeid
JOIN Relationship ON f.RelationshipID = Relationship.RelationshipID
WHERE v.datevisited
BETWEEN CURDATE( ) - INTERVAL 1 YEAR
AND CURDATE( )