简体   繁体   中英

SQL Server query on two tables

I have a SQL Server database with two tables, table 1 lists membership records and table 2 lists the names for each membership record. There can be more than one person in table 2 per record in table 1.

  • table_1.MembershipNumber
  • table_1.MemberType
  • table_1.StartDate

  • table_2.MembershipNumber

  • table_2.FirstName
  • table_2.LastName
  • table_2.Age

I would like to create a view which filters out records in table 1 where the age of anyone in table 2 is over the age of, say, 50.

CREATE VIEW [dbo].[vw_Membership]
  AS 
Select t.MembershipNumber ,tt.FirstName,tt.LastName 
    from MembershipNumber_table_1 t
    INNER JOIN  MembershipNumber_table_2 tt
    ON t.MembershipNumber = tt.MembershipNumber 
        AND MemberType = 'A'
    WHERE (DATEDIFF(yy,MembershipNumber_table_2.Age,GetDate()) -
CASE WHEN((MONTH(MembershipNumber_table_2.Age)*100 + DAY(MembershipNumber_table_2.Age)) > (MONTH(GetDate())*100 + DAY(GetDate()))) THEN 1 ELSE 0 END)>50
GO

OR

WHERE DATEDIFF(YEAR, MembershipNumber_table_2.Age, GETDATE())>50

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM