此查询
SELECT PA.refPatient_id
,MAX(PA.datee) AS datee
,PR.temporary,PA.statue
FROM PatientClinicActs AS PA
,PatientStatueReasons AS PR
WHERE PA.refClinic_id = 25
AND PA.refreason_id = PR.reason_id
GROUP BY PA.refPatient_id,PA.statue,PR.temporary
返回以下结果:
refPatient_id datee temporary statue
----------- ----------------------- ------ -----
14706 2008-12-01 11:01:00 1 0
14707 2009-05-18 16:21:00 1 0
14708 2009-07-15 09:46:00 1 0
14708 2009-07-29 16:12:00 1 0
14716 2009-11-09 12:29:00 0 0
14716 2009-09-01 11:15:00 1 0
14716 2009-09-29 16:44:00 1 1
但我希望得到这些结果:
refPatient_id datee temporary statue
----------- ----------------------- ------ -----
14706 2008-12-01 11:01:00 1 0
14707 2009-05-18 16:21:00 1 0
14708 2009-07-29 16:12:00 1 0
14716 2009-11-09 12:29:00 0 0
有什么区别? =>我在这些结果中为每个refPatient_id提供了最新的行。 我该怎么办才能得到这些结果?
答案 0 :(得分:3)
尝试这样的事情
SELECT PA.refPatient_id,
PA.datee,
PR.temporary,
PA.statue
FROM PatientClinicActs AS PA INNER JOIN
(
SELECT PA.refPatient_id,
MAX(PA.datee) AS datee
FROM PatientClinicActs AS PA
WHERE PA.refClinic_id = 25
GROUP BY PA.refPatient_id,PA.statue,PA.datee,
) AS MaxDates ON PA.refPatient_id = MaxDates.refPatient_id AND PA.datee = MaxDates.datee INNER JOIN
PatientStatueReasons AS PR ON PA.refreason_id = PR.reason_id
您需要先获得每位患者的最长日期,然后加入。
答案 1 :(得分:1)
而不是交叉连接
FROM PatientClinicActs AS PA
,PatientStatueReasons AS PR
你可以试试内连接
FROM PatientClinicActs AS PA
INNER JOIN PatientStatueReasons AS PR
ON PA.refreason_id = PR.reason_id
WHERE PA.refClinic_id = 25
答案 2 :(得分:0)
对于这种情况,还有另一种方法可以使用SQL Server Ranking functions来获取最新的记录。
我已使用DENSE_RANK()
作为答案,但您可以使用RANK()
代替您的特定问题。
(注意:以下代码未经过测试。如果您要为表提供架构,我会测试样本数据)
;with RankedResult as (
SELECT
PA.refPatient_id
, PA.datee
, PR.temporary,
, PA.statue
--; Last datee has the lowest rank value of 1,
, dense_rank() over
(partition by PA.refPatient_id order by PA.datee desc) as [Rank]
FROM PatientClinicActs AS PA
join PatientStatueReasons AS PR on PA.refreason_id = PR.reason_id
WHERE PA.refClinic_id = 25
)
select distinct *
from RankedResult
--; Get only the last result.
where [Rank] = 1
答案 3 :(得分:-2)
将PA.datee从group by子句
中取出