select" group by"在特定列上,但显示其他列以及逐列

时间:2015-06-05 11:10:09

标签: sql-server sql-server-2008

我希望仅基于encounter,medicationname的群组获取所有数据 列数据..

select encounter,medicationname,count(*) as freq,labdate,result 
from Medications where (labdate between @admitdate and DATEDIFF(dd,24,@admitdate)) 
group by encounter,medicationname having count(*)>2

我有像

这样的记录
encounter   medicationname  freq
8604261         ACC               3 

现在根据这些数据,我想得到

这是我想要的输出

encounter   medicationname  labtime     result
8604261       ACC              2015-05-22    18
8604261       ACC              2015-07-23    23
8604261       ACC              2015-09-09    27

3 个答案:

答案 0 :(得分:1)

您可以使用PostDataAsync作为窗口函数,如下所示:

COUNT()

我会注意到我认为;With Counted as ( SELECT encounter,medicationname,labdate,result, COUNT(*) OVER (PARTITION BY encounter,medicationname) as cnt from Medications where (labdate between @admitdate and DATEDIFF(dd,24,@admitdate)) ) select encounter,medicationname,labdate,result from Counted where cnt > 2 1 也可能是错误的,但由于我没有您的数据,输入和实际规格,我还是离开了就像现在一样。

1 DATEDIFF会返回DATEDIFF,但您在与明显为int的列进行比较时会使用它。 date在这里可能是更可能需要的功能,但正如我所说,我没有完整的信息可以继续。

答案 1 :(得分:0)

select encounter,medicationname,count(*) as freq,labdate,result 
from Medications 
where (labdate between @admitdate and DATEDIFF(dd,24,@admitdate)) 
group by encounter,medicationname having count(*) > 2

答案 2 :(得分:0)

如果我理解你正确地问你需要的是这个

;WITH CTE AS 
(
select encounter,medicationname,count(*) as freq,labdate,result 
from Medications where (labdate between @admitdate and DATEDIFF(dd,24,@admitdate)) 
group by encounter,medicationname having count(*) > 2
)
select encounter,medicationname,labdate,result 
from Medications M
INNER JOIN CTE C
ON M.encounter = C.encounter
AND M.medicationname = C.medicationname
where (labdate between @admitdate and DATEDIFF(dd,24,@admitdate)) 

或更好地使用COUNT()OVER()

;WITH CTE AS
( 
    SELECT encounter,medicationname,COUNT(*) OVER(PARTITION BY encounter,medicationname)as freq,labdate,result 
    FROM Medications
    WHERE (labdate between @admitdate and DATEDIFF(dd,24,@admitdate)) 
)
SELECT * FROM CTE
WHERE freq > 2