[英]How can I get the value of non-aggregated column with an aggregated column?
I have this sample table: 我有这个样本表:
ColA ColB ColC
CBCP 25 popx
ABC1 10 ppp1
ABC1 25 ppxx
CBCP 30 xm2x
from there I would like to get these columns 从那里我想得到这些专栏
ColA ColB ColC
ABC1 25 ppxx
CBCP 30 xm2x
what I would want is to get the row with max ColB.. But I am getting an error when I try to include the ColC in my query: 我想要的是获得max ColB的行..但是当我尝试在我的查询中包含ColC时出现错误:
select ColA, max(ColB), ColC
from tblCaseDev
where ColB > getdate() group by ColA
this is my error.. 这是我的错误..
Msg 8120, Level 16, State 1, Line 1
Column 'tblCaseDev.ColC' is invalid in the
select list because it is not contained in either
an aggregate function or the GROUP BY clause.
hope someone could help me.. thanks in advance.. 希望有人能帮助我..提前谢谢..
SELECT
CaseNo,Date,Remarks,
(SELECT max(cast(Date as datetime)) FROM tblCaseDev subc WHERE subc.CaseNo=c.CaseNo Group by c.CaseNo) AS MaxEntryDate
FROM tblCaseDev c
order by CaseNo
You want to use the row_number()
window function: 您想使用row_number()
窗口函数:
select CaseNo, "Date", Remarks
from (select t.*, row_number() over (partition by caseno order by date desc) as seqnum
from tblCaseDev t
where date > getdate()
) t
where seqnum = 1;
EDIT: 编辑:
You can do this the old fashioned way if you don't have row_number()
: 如果你没有row_number()
你可以用老式的方式做到这一点:
select t.*
from tblCaseDev t join
(select caseno, max(date) as maxdate
from tblCaseDev
group by caseno
) tsum
on t.caseno = tsum.caseno and t.date = tsum.maxdate
You can create an aggregate query first, then join the original table to the aggregate query. 您可以先创建聚合查询,然后将原始表连接到聚合查询。
Example: 例:
SELECT
A.CaseNo,
A.Date,
B.Remarks
FROM (
SELECT
CaseNo,
MAX(Date)
FROM tblCaseDev
WHERE Date > GetDate()
GROUP BY CaseNo
) A
JOIN tblCaseDev B
ON A.CaseNo = B.CaseNo
AND A.Date = B.Date
You can use ROW_NUMBER()
which generates sequential number for every group ColA
and ordered by ColB
in descending. 您可以使用ROW_NUMBER()
为每个组ColA
生成序列号, ColA
ColB
以降序排序。
SELECT ColA, ColB, ColC
FROM
(
SELECT ColA, ColB, ColC,
ROW_NUMBER() OVER(PARTITION BY ColA
ORDER BY ColB DESC) rn
FROM tablename
) x
WHERE rn = 1
If you want to get multiple records which ties up in ColB
, you may want to change it to DENSE_RANK()
. 如果要获取多个与ColB
记录,可能需要将其更改为DENSE_RANK()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.