Solved

SQL Server MIN Funtion

Posted on 2013-12-26
6
329 Views
Last Modified: 2013-12-30
Hi,

I have the SQL below. I am trying to get only one row with MiniMum Date (First Med Given Date and time). But it is returning multiple rows. Therefore, I am using Top 1 Function. Is there any other way to do this without Top Funtion? Please advise. Thanks

SELECT TOP 1
            DIS.EID,
            DIS.Institution,
            DIS.MRN,
            DIS.Account,
            DIS.AdmitDateTime,
            DIS.ERAdmitDtTm AS 'ED Received Date Time',
            Meds.[First Abx Admin Date],
            Meds.DrugName AS 'Antibiotic Name',
            (CASE      
                  WHEN (Meds.[First Abx Admin Date]) <= dateadd(hh,3, (CASE WHEN DIS.ERAdmitDtTm IS NULL THEN Dis.AdmitDateTime ELSE DIS.ERAdmitDtTm END))
                  THEN 'Y'
                  Else 'N'
            END) as ArrivalAbx
FROM      
            VISITPT_ALL_DIS AS DIS
            LEFT OUTER JOIN
                  (      SELECT
                              Med.EID,
                              Med.Account,
                              Med.DrugName,
                              MIN(MED.LastAdminDateTime)AS 'First Abx Admin Date'
                        FROM
                              MedAdminMAR_All_Adm AS MED
                        WHERE
                              Med.DrugID IN ( 'ACYC500I','AMIK500I','AMPH50I','AMPH50IL')
                        GROUP BY
                              Med.EID,
                              Med.Account,
                              Med.AdmitDateTime,
                              Med.DrugName
                        )Meds
            ON DIS.Account = Meds.Account
WHERE
      DIS.PatientType = 'IN'
      AND DIS.AccountStatus = 'DIS'  
ORDER BY
      DIS.Institution,
      DIS.MRN,
      DIS.Account,
      DIS.AdmitDateTime ,
      Meds.[First Abx Admin Date]
0
Comment
Question by:rustypoot
6 Comments
 
LVL 65

Assisted Solution

by:Jim Horn
Jim Horn earned 250 total points
ID: 39741056
The only Min() I see here is in a subquery, which is on the right side of a LEFT JOIN, which means all rows on the LEFT side (VISITPT_ALL_DIS AS DIS) will be returned in the result set.

So ... if you only want to return the one row, for starters change the LEFT JOIN to an INNER JOIN (or just JOIN).

Also, if DIS has a date that is the equivalent of MED.LastAdminDateTime, then you'll have to add that relationship to the JOIN clause, so the line below needs to change to the line below that:

             ON DIS.Account = Meds.Account

Open in new window

             ON DIS.Account = Meds.Account AND DIS.??Date = Meds.[First Abx Admin Date'] 

Open in new window

0
 
LVL 13

Expert Comment

by:AielloJ
ID: 39741751
rustypoot

Without knowing more about your data model, it appears the root cause of the problem is a lack of the proper clauses in the WHERE clause.  I'm assuming 'Account' is the patient you are trying to get the one row for.

Since 'Account' is not in the WHERE clause, the first row for some random patient is probably being returned.

Best regards,

AielloJ
0
 
LVL 32

Expert Comment

by:awking00
ID: 39742414
select whatever from
(select whatever, row_number() over (partition by eid order by [first med given date and time] desc) rn
from yourtablejoin)
where rn = 1
0
Complete VMware vSphere® ESX(i) & Hyper-V Backup

Capture your entire system, including the host, with patented disk imaging integrated with VMware VADP / Microsoft VSS and RCT. RTOs is as low as 15 seconds with Acronis Active Restore™. You can enjoy unlimited P2V/V2V migrations from any source (even from a different hypervisor)

 

Author Comment

by:rustypoot
ID: 39746541
Jim,

Thanks for the reply. But even if I change the JOIN to INNER JOIN, I get same # of rows. Also, there is no equivalent date to join on..
0
 
LVL 32

Expert Comment

by:awking00
ID: 39746636
Can you provide some relevant sample data (i.e. eliminate the extraneous fields and only include data meeting your filtering requirements other than the dates in question) and your expected output.
0
 
LVL 75

Accepted Solution

by:
Anthony Perkins earned 250 total points
ID: 39746642
Since you are getting multiple rows, they are probably coming from the JOIN'd table.  So you need to ask yourself
1. Why you are including Med.EID when you are not using it anywhere, either in the SELECT or JOIN.
2. Since you are selecting DrugName, which one do you want returned if there are multiple rows with a different DrugName?  The one with the oldest LastAdminDateTime?  If so what happens if there are two with the same LastAdminDateTime?
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I'm trying, I really am. But I've seen so many wrong approaches involving date(time) boundaries I despair about my inability to explain it. I've seen quite a few recently that define a non-leap year as 364 days, or 366 days and the list goes on. …
This article describes how to use the timestamp of existing data in a database to allow Tableau to calculate the prior work day instead of relying on case statements or if statements to calculate the days of the week.
Internet Business Fax to Email Made Easy - With  eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, f…
With the power of JIRA, there's an unlimited number of ways you can customize it, use it and benefit from it. With that in mind, there's bound to be things that I wasn't able to cover in this course. With this summary we'll look at some places to go…

910 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now