[英]MAX Column Value for Distinct Value on Different column SQL Server 2008 R2
I have data that comes in the following format: 我有以下格式的数据:
VISIT ID | DATETIME | ORDER NUM
123 | 2012-01-01 11:21:00:0000 | 111
123 | 2012-01-01 12:15:00:0000 | 223
...
So it is entirely possible for the same visit id to have multiple orders for the same exact thing, for example, two different orders for discharge, one might get canceled, and replaced by another. 因此,相同的访问ID完全有可能对同一事物具有多个订单,例如,两个不同的卸货订单,一个可能被取消,然后被另一个替换。
What I want for a result would be something like the following: 我想要的结果将是如下所示:
VISIT ID | DATE | TIME | ORDER NUM
123 | 2012-01-01 | 12:15:00 | 223
...
All order numbers will be distinct, so if someone gets multiple orders for an x-ray, all order numbers will be unique. 所有订单号都是不同的,因此,如果某人获得X射线检查的多个订单,则所有订单号都是唯一的。 I am trying to obtain the MAX()
order number for a visit id, so that the results only output one row as shown above. 我正在尝试获取访问ID的MAX()
订单号,以便结果仅输出一行,如上所示。
I have been looking at the following links for some guidance but unfortunately I am most definitely missing something and not connecting the dots. 我一直在寻找以下链接以获取一些指导,但不幸的是,我绝对会缺少某些东西,而且一点也不联系。
Max Value on Distinct column value 不同列值的最大值
one of my own former questions - this will not work because almost all Discharge orders get discontinued when the patient actually gets discharged. 我以前的问题之一 -这将行不通,因为当患者实际出院时,几乎所有的出院命令都将中断。
Here is the code that I have so far: 这是我到目前为止的代码:
select episode_no
, CAST(ent_dtime as DATE) as [Date]
, CAST(ent_dtime as time) as [Time]
, ord_no = (select top 1 t1.ord_no from smsmir.sr_ord t1)
from smsmir.sr_ord
WHERE svc_desc = 'DISCHARGE TO'
AND episode_no < '200000000'
group by episode_no, ord_no, ent_dtime
order by episode_no
I have also tried the following: 我也尝试了以下方法:
select episode_no
, CAST(ent_dtime as DATE) as [Date]
, CAST(ent_dtime as time) as [Time]
, MAX(ord_no)
from smsmir.sr_ord
WHERE svc_desc = 'DISCHARGE TO'
AND episode_no < '200000000'
group by episode_no, ord_no, ent_dtime
order by episode_no
Any direction would be great, thank you. 任何方向都很好,谢谢。
EDIT 编辑
When I use the following query: 当我使用以下查询时:
SELECT EPISODE_NO
, MAX(ORD_NO)
FROM SMSMIR.SR_ORD
WHERE SVC_DESC = 'DISCHARGE TO'
AND EPISODE_NO < '20000000'
GROUP BY EPISODE_NO
I get what I need, but when I add in the datetime
field it all goes to plop. 我得到了我需要的东西,但是当我在datetime
字段中添加内容时,一切就变得扑朔迷离了。
Try this query: 试试这个查询:
SELECT *
FROM (
SELECT EPISODE_NO
, ORD_NO
, [DATE TIME COLUMN]
, ROW_NUMBER() OVER(PARTITION BY EPISODE_NO ORDER BY ORD_NO) AS RowNum
FROM SMSMIR.SR_ORD
WHERE SVC_DESC = 'DISCHARGE TO'
AND EPISODE_NO < '20000000'
) src
WHERE src.RowNum = 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.