如何使用聚合列获取非聚合列的值?

时间:2013-08-28 01:31:10

标签: sql sql-server

我有这个样本表:

ColA   ColB   ColC
CBCP    25    popx
ABC1    10    ppp1
ABC1    25    ppxx
CBCP    30    xm2x

从那里我想得到这些专栏

ColA   ColB   ColC
ABC1    25    ppxx
CBCP    30    xm2x

我想要的是获取max ColB的行..但是当我尝试在我的查询中包含ColC时出现错误:

select ColA, max(ColB), ColC
from tblCaseDev
where ColB > getdate() group by ColA

这是我的错误..

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.

希望有人能帮助我..提前感谢..

4 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

您想使用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;

编辑:

如果您没有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

答案 2 :(得分:1)

您可以先创建聚合查询,然后将原始表连接到聚合查询。

示例:

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

答案 3 :(得分:0)

您可以使用ROW_NUMBER()为每个组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

如果您希望获得与ColB相关的多条记录,您可能需要将其更改为DENSE_RANK()