两个表上的SQL Server查询

时间:2014-07-09 15:43:20

标签: sql sql-server database

我有一个带有两个表的SQL Server数据库,表1列出了成员资格记录,表2列出了每个成员资格记录的名称。表1中每个记录的表2中可以有多个人。

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

  • table_2.MembershipNumber

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

我想创建一个过滤掉表1中记录的视图,其中表2中任何人的年龄超过50岁。

1 个答案:

答案 0 :(得分:0)

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