Tsql T-Sql,如何获得这些结果?
这个问题Tsql T-Sql,如何获得这些结果?,tsql,Tsql,这个问题 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
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 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
有什么区别?=>我有这些结果中每个参考患者id的最新行。
我应该运行什么来获得这些结果?将PA.datee从group by子句中取出尝试类似的方法
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
您需要首先获得每位患者的最大日期,然后加入该日期。而不是交叉加入
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
对于这种情况,还有另一种方法可以通过使用获取最新记录 我已经用过我的答案,但你可以用,代替你的特殊问题。
(注意:下面的代码未经测试。如果要为表提供架构,我将使用示例数据进行测试)
是否要获取给定REF患者Id的最新信息?在上面做一个rank()并选择rank==1应该起作用的位置。我想为每个refPatient_id获取最新的行。请用rank写一个例子好吗?您的14708结果:它们在第一个结果集中看起来是错误的。您不应该通过该groupingok的查询获得该结果。你有什么建议吗?或者我应该使用游标编写循环?@uzay95:advice=post schema and code对于某些患者,它仍然有多行。这可能是因为在PatientClinicats中出现了多次的最大日期,或者是指向PatientStatueResons的链接包含了患者的多个条目,在这种情况下,您必须决定如何选择适当的记录。什么能让它成为你需要的?我投票否决了你因为我误读了。。。显然无法撤消它,所以我投票支持您为fairnessOk“检索具有最高值的行”。如果我检索ref patient_id、refReason_id和datee,我可以为某些患者执行多个操作。因为它们可能是被动的(雕像=0),然后是主动的(雕像=1),有一些原因。然后将其更改为仅选择您需要的雕像0或1非常感谢先生。我从你身上学到了很多,现在还在学习。你的评论对我总是很有价值的。感谢againIt不是交叉连接-它是使用非ANSI连接语法的内部连接。