在t-sql代码中出现MAX语句问题

时间:2011-10-01 19:04:32

标签: sql sql-server tsql sql-server-2008

这是代码:

Select BCPP.*
from ViewPBCPP   BCPP
inner join
( 
Select MBC.PC     PC
      ,MRT.Name   CT
      ,Max(dbo.CalcDatefromUTC(MBC.CreatedDate)) as LRDate
from TableBACC    MBC

inner join TableSC.RT   MRT
ON MBC.RTid = MRT.id
where MBC.Isdeleted = 'False'
and MBC.PC <> 'NULL'
Group by MBC.PC
        ,MRT.Name
) MBCR
ON BCPP.P_id = MBCR.PC
and BCPP.CreatedDate = MBCR.LRDate
and BCPP.CT = MBCR.CT

现在Max(dbo.CalcDatefromUTC(MBC.CreatedDate))实际上是一个函数

上述查询适用于Max(dbo.CalcDatefromUTC(MBC.CreatedDate))

现在我写的时候

Max(dbo.CalcDatefromUTC(MBC.CreatedDate)) + Min(dbo.CalcDatefromUTC(MBC.CreatedDate))

我无法从上面写的查询中提取任何值

如果我只写

(dbo.CalcDatefromUTC(MBC.CreatedDate))

它给我一个错误,它不包含聚合函数或按函数分组

我其实想要这个

(dbo.CalcDatefromUTC(MBC.CreatedDate))

这样我就可以使用这个函数的所有值,而不仅仅是它的MAX值

如何更改上面编写的代码以实现我的目标?

任何??

1 个答案:

答案 0 :(得分:0)

dbo.CalcDatefromUTC(MBC.CreatedDate)列表中不能SELECT,因为它不在MBC.CreatedDate列表中,因为GROUP BY列表中没有MAX(MBC.CreatedDate)

你可以拥有dbo.CalcDatefromUTC(MAX(MBC.CreatedDate)) as LRDate ,因为它在thta列上使用了聚合函数(MAX)。你也可以:

MAX(dbo.CalcDatefromUTC(MBC.CreatedDate)) as LRDate

实际上是相同的(虽然可能更快),如:

MBC.CreatedDate

从您的评论中,我认为上述内容并不是很有帮助。也许按Select BCPP.* from ViewPBCPP BCPP inner join ( Select MBC.PC PC ,MRT.Name CT ,dbo.CalcDatefromUTC(MBC.CreatedDate) as LRDate from TableBACC MBC inner join TableSC.RT MRT ON MBC.RTid = MRT.id where MBC.Isdeleted = 'False' and MBC.PC <> 'NULL' Group by MBC.PC ,MBC.CreatedDate --- added ,MRT.Name ) MBCR ON BCPP.P_id = MBCR.PC and BCPP.CreatedDate = MBCR.LRDate and BCPP.CT = MBCR.CT 分组也是你想要的:

{{1}}