我有一张桌子可以捕捉用户体重和体脂百分比。我正在寻找一个SQL查询,它将获得所有用户以及他们的第一个和最后一个条目(所以我可以锻炼总体重减去等。)
表结构如下:
UserName NVARCHAR(128)
DateTimeStamp DateTime
BodyWeight DECIMAL(18,2)
BodyFatPercentage DECIMAL(18,2)
我希望返回的数据如下:
Username|First Date|Weight|Body Fat Percentage|Last Date|Weight|Body Fat Percentage|
John|21 January 2015|80|25|14 February 2015|76|22|
Mary|15 January 2015|55|19|12 February 2015|53|18|
Danny|10 January 2015|75|23|10 February 2015|70|19|
Saul|05 January 2015|77|28|13 February 2015|76|27|
提前致谢
答案 0 :(得分:7)
您可以为每个用户分配升序和降序行号。该用户的第一个条目具有升序row_number
1,最后一个条目具有降序row_number
1.例如:
select UserName
, max(case when rn1 = 1 then DateTimeStamp end) as FirstDate
, max(case when rn1 = 1 then BodyWeight end) as BW
, max(case when rn1 = 1 then BodyFatPercentage end) as BFP
, max(case when rn2 = 1 then DateTimeStamp end) as LastDate
, max(case when rn2 = 1 then BodyWeight end) as BW
, max(case when rn2 = 1 then BodyFatPercentage end) as BFP
from (
select row_number() over (
partition by UserName
order by DateTimeStamp) rn1
, row_number() over (
partition by UserName
order by DateTimeStamp desc) rn2
, *
from YourTable
) as SubQueryAlias
group by
UserName
答案 1 :(得分:4)
假设MSSQL 2005或更新版本,您可以使用APPLY
运算符:
SELECT
users.Username,
first.DateTimeStamp AS FirstDate,
first.BodyWeight AS FirstWeight,
first.BodyFatPercentage AS FirstPercentage,
last.DateTimeStamp AS LastDate,
last.BodyWeight AS LastWeight,
last.BodyFatPercentage AS LastPercentage
FROM (
SELECT DISTINCT Username
FROM User
) AS users
CROSS APPLY (
SELECT TOP 1 *
FROM User
WHERE User.Username = users.Username
ORDER BY DateTimeStamp ASC
) AS first
CROSS APPLY (
SELECT TOP 1 *
FROM User
WHERE User.Username = users.Username
ORDER BY DateTimeStamp DESC
) AS last
好吧它变得有点难看,因为我必须在User
表的子查询中选择一个不同用户名列表,在一个规范化的数据库中,你可能已经将用户放在一个单独的表中。
APPLY
运算符为我们提供了一种方便的方法来为每个用户执行表值查找,即我们可以以干净和结构化的方式为每个用户获取第一行和最后一行。