我需要以下查询的帮助。
我有一个表M,它包含membre_number,first_name,Last_name,Date_birth 我需要知道meny成员的年龄大于所有成员first_name的平均值。请注意,许多成员都被命名为保罗。
我试过以下
SELECT date_nais
FROM membre
WHERE prenom_membre = 'paul'
SELECT AVG(convert(GETDATE()-membre.date_nais)/365.242199)
FROM membre;
答案 0 :(得分:0)
试试吧,
DECLARE @M table
(
membre_number int identity,
first_name varchar(10),
Last_name varchar(10),
Date_birth date
)
INSERT @M (first_name, Last_name, Date_birth) Values
('Paul', 'Surname 1' , '20170101')
,('dadada', 'Surname 1' , '20130101')
,('Paul', 'Surname 2' , '20090301')
,('Paul', 'Surname 3' , '19890401')
,('Paul', 'Surname 4' , '19300521')
,('Alana', 'XX' , '19750521')
SELECT *
,DATEDIFF(Year,Date_birth,Getdate()) Age
,Avg(Cast(DATEDIFF(Year,Date_birth,Getdate()) as decimal(5,2))) Over (Partition by first_name) Agv_ByName
,Avg(Cast(DATEDIFF(Year,Date_birth,Getdate()) as decimal(5,2))) Over (Partition by 1) AllUsers
,Case when first_name = 'Paul' THEN
Avg(Cast(DATEDIFF(Year,Date_birth,Getdate()) as decimal(5,2))) Over (Partition by first_name)
Else NULL end Agv_Pauls_age
FROM
@M
结果
membre_number first_name Last_name Date_birth Age Agv_ByName AllUsers Agv_Pauls_age
------------- ---------- ---------- ---------- ----------- --------------------------------------- --------------------------------------- ---------------------------------------
6 Alana XX 1975-05-21 42 42.000000 28.166666 NULL
2 dadada Surname 1 2013-01-01 4 4.000000 28.166666 NULL
3 Paul Surname 2 2009-03-01 8 30.750000 28.166666 30.750000
4 Paul Surname 3 1989-04-01 28 30.750000 28.166666 30.750000
5 Paul Surname 4 1930-05-21 87 30.750000 28.166666 30.750000
1 Paul Surname 1 2017-01-01 0 30.750000 28.166666 30.750000
(6 rows affected)
或者让Paul AVg参与所有行
;with cte as (
SELECT *
,DATEDIFF(Year,Date_birth,Getdate()) Age
,Avg(Cast(DATEDIFF(Year,Date_birth,Getdate()) as decimal(5,2))) Over (Partition by first_name) Agv_ByName
,Avg(Cast(DATEDIFF(Year,Date_birth,Getdate()) as decimal(5,2))) Over (Partition by 1) AllUsers
,Case when first_name = 'Paul' THEN
Avg(Cast(DATEDIFF(Year,Date_birth,Getdate()) as decimal(5,2))) Over (Partition by first_name)
Else NULL end Agv_Pauls_age
FROM
@M
)
SELECT
membre_number
,first_name
,Last_name
,Date_birth
,Age
,Agv_ByName
,AllUsers
,MAX(IsNUll(Agv_Pauls_age,0)) Over (Partition By 1 ) Agv_Pauls_age
from cte
结果
membre_number first_name Last_name Date_birth Age Agv_ByName AllUsers Agv_Pauls_age
------------- ---------- ---------- ---------- ----------- --------------------------------------- --------------------------------------- ---------------------------------------
6 Alana XX 1975-05-21 42 42.000000 28.166666 30.750000
2 dadada Surname 1 2013-01-01 4 4.000000 28.166666 30.750000
3 Paul Surname 2 2009-03-01 8 30.750000 28.166666 30.750000
4 Paul Surname 3 1989-04-01 28 30.750000 28.166666 30.750000
5 Paul Surname 4 1930-05-21 87 30.750000 28.166666 30.750000
1 Paul Surname 1 2017-01-01 0 30.750000 28.166666 30.750000
(6 rows affected)