Here are three possible methods to do what you want to do.
Here is a row_number()
method:
with p as (
SELECT M.ProcedureID, M.SegmentDateTime, M.PriceID,
L.DrugID, L.NdcDinNumber, L.Name, M.DeptCorporation, M.InpAmount,
M.InpCount, M.OutAmount, M.OutCount,
row_number() over (partition by procedureID order by (select NULL)) as seqnum,
SUM(InpCount) OVER (PARTITION BY ProcedureID) as INtotal,
SUM(InpAmount) OVER (PARTITION BY ProcedureID) as IN$Total,
SUM(OutCount) OVER (PARTITION BY ProcedureID) as OUTtotal,
SUM(OutAmount) OVER (PARTITION BY ProcedureID) as OUT$Total,
SUM(InpCount + OutCount) OVER (PARTITION BY ProcedureID) as TotalCount,
SUM(InpAmount + OutAmount) OVER (PARTITION BY ProcedureID) as TotalAmount
AVG(InpCount + OutCount) OVER (PARTITION BY ProcedureID) as AverageCount,
AVG(InpAmount + OutAmount) OVER (PARTITION BY ProcedureID) as AverageAmount
FROM BarRevenueByProcedurePriceInfo M LEFT JOIN
DPhaDrugData L
ON M.ProcedureID = L.BillNumber
WHERE DeptID = '010.4730' AND SegmentDateTime = '2013-12-31 00:00:00.000' AND
(M.InpCount > '0' or M.OutCount > '0')
)
select p.*
from p
where seqnum = 1
ORDER BY ProcedureID;
You might want to remove seqnum
from the list of removed columns.
Another method you can use is to just add distinct
after the select
.
Finally, I suspect your query is equivalent to:
SELECT M.ProcedureID, M.SegmentDateTime, M.PriceID,
L.DrugID, L.NdcDinNumber, L.Name, M.DeptCorporation, M.InpAmount,
M.InpCount, M.OutAmount, M.OutCount,
SUM(InpCount) as INtotal,
SUM(InpAmount) as IN$Total,
SUM(OutCount) as OUTtotal,
SUM(OutAmount) as OUT$Total,
SUM(InpCount + OutCount) as TotalCount,
SUM(InpAmount + OutAmount) as TotalAmount
AVG(InpCount + OutCount) as AverageCount,
AVG(InpAmount + OutAmount) as AverageAmount
FROM BarRevenueByProcedurePriceInfo M LEFT JOIN
DPhaDrugData L
ON M.ProcedureID = L.BillNumber
WHERE DeptID = '010.4730' AND SegmentDateTime = '2013-12-31 00:00:00.000' AND
(M.InpCount > '0' or M.OutCount > '0')
GROUP BY M.ProcedureID, M.SegmentDateTime, M.PriceID,
L.DrugID, L.NdcDinNumber, L.Name, M.DeptCorporation, M.InpAmount,
M.InpCount, M.OutAmount, M.OutCount;