从查询结果中选择?

时间:2011-11-21 13:33:10

标签: sql database sql-server-2005 tsql

我有这样的查询:

SELECT Weighings.Member, MIN(Sessions.DateTime) AS FirstDate, MAX(Sessions.DateTime) AS LastDate
FROM Weighings AS Weighings INNER JOIN
     Sessions ON Sessions.SessionGUID = Weighings.Session
WHERE     (Sessions.DateTime >= '01/01/2011')
GROUP BY Weighings.Member
ORDER BY Weighings.Member

它返回:

Member | FirstDate | LastDate
Blah   | 01/01/11  | 06/07/11
Blah2  | 02/03/11  | 05/07/11

我需要获取表Weight_kg中的单元格Weighings的值,以获取返回值FirstDateLastDate,以便得到如下结果:

Member | FirstWeight | LastWeight
Blah   | 150Kg       | 60KG
Blah2  | 70Kg        | 72KG

我已经尝试了所有组合的东西,但是无法解决这个问题,任何想法?

修改

表:

Sessions
______________________
SessionGUID | DateTime
----------------------
12432524325 | 01/01/11
12432524324 | 01/08/11
12432524323 | 01/15/11
34257473563 | 03/05/11
43634574545 | 06/07/11

Weighings
_____________________________________
Member      | Session     | Weight_kg
-------------------------------------
vffd8fdg87f | 12432524325 | 150
vffd8fdg87f | 12432524324 | 120
vffd8fdg87f | 12432524323 | 110
ddffv89sdv8 | 34257473563 | 124
32878vfdsv8 | 43634574545 | 75

3 个答案:

答案 0 :(得分:6)

;with C as
(
  select W.Member,
         W.Weight_kg,
         row_number() over(partition by W.Member order by S.datetime desc) as rnLast,
         row_number() over(partition by W.Member order by S.datetime asc) as rnFirst
  from Weighings as W
    inner join Sessions as S
      on S.sessionguid = W.Session and
         S.DateTime >= '20110101'
)
select CF.Member,
       CF.Weight_kg as FirstWeight,
       CL.Weight_kg as LastWeigth
from C as CF
  inner join C as CL
    on CF.Member = CL.Member
where CF.rnFirst = 1 and
      CL.rnLast = 1

在此尝试:http://data.stackexchange.com/stackoverflow/q/118518/

答案 1 :(得分:2)

您可以使用RANK..OVER stmt(仅适用于SQL 2k5 +)

select fw.Member, st.Weight, en.Weight
from
(
    select Member, Weight, RANK() OVER(PARTITION BY Member ORDER BY Weight) rnk
    from Weighings
) st
inner join 
(
    select Member, Weight, RANK() OVER(PARTITION BY Member ORDER BY WeightDESC) rnk
    from Weighings
) en on en.Member= st.Member and st.rnk = 1 and en.rnk = 1

答案 2 :(得分:-1)

你有两种可能性。

如果你想重复使用第一次SELECT,我建议创建临时表

CREATE TEMPORARY TABLE `tmpTable` AS SELECT /*the first select*/ ;

/*and then*/

SELECT * FROM `tmpTable` /*the second select from the first select*/

如果您只需要第一次选择

SELECT first.* 
FROM (SELECT /*the first select*/) AS first