1

我有这个示例表:

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

从那里我想得到这些列

ColA   ColB   ColC
ABC1    25    ppxx
CBCP    30    xm2x

我想要的是获得最大 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

4 回答 4

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
于 2013-08-28T03:05:08.593 回答
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
于 2013-08-28T01:35:19.180 回答
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
于 2013-08-28T01:38:57.833 回答
0

您可以使用ROW_NUMBER()which 为每个组生成序列号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().

于 2013-08-28T01:34:12.710 回答