简体   繁体   中英

SQL - Group By unique column combination

I am trying to write a script that will return the latest values for a unique documentid-physician-patient triplet. I need the script to act similar to a group by statement, except group by only works with one column at a time. I need to date and status information for only the most recent unique triplet. Please let me know what you will need to see from me to help. Here is the current, very bare, statement:

    SELECT
        TransmissionSend.CreateTimestamp,
        TransmissionSendItem.Status,
        TransmissionSendItem.PhysicianId,
        TransmissionSendItem.DocumentIdDisplay,
        Utility.SqlFunctions_NdnListToAccountList(TransmissionSendItem.NdocNum) AS AccountNum
    FROM
        Interface_SFAX.TransmissionSend,
        Interface_SFAX.TransmissionSendItem
    WHERE
        TransmissionSend.ID = TransmissionSendItem.childsub --I don't know exactly what this does, I did not write this script. It must stay here though for the exact results.

    ORDER BY TransmissionSend.CreateTimestamp DESC -- In the end, each latest result of the unique triplet will be ordered from most recent to oldest in return

My question is, again, how can I limit results to only the latest status for each physician id, document id, and account number combination?

First select the MAX(date) with the documentid GROUP BY documentid then select all data from the table by the first select result for example with an inner join.

SELECT table.additionalData, J.id, J.date
FROM table
INNER JOIN (SELECT id, MAX(date) AS date 
            FROM table GROUP BY id) AS J 
ON J.id = table.id 
AND J.date /* this is the max date */ = table.date

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM