使用SQL Server 2012 ....此代码作为独立脚本运行,但我需要在iif(...)
中作为更大脚本的一部分嵌套在Case...when
内返回的值:
with GroupedValues (Value, Frequency, SelectingCriteria) AS
(Select
Table1.Cost as Value,
Count(*) as Frequency,
Table2.AccountNumber as SelectingCriteria
from Table1, Table 2
)
Group by Table1.Cost, Table2.AccountNumber)
Select
Max(Value) as Value
From GroupedValues a INNER JOIN
(select Max(Frequency) AS MaxFrequency
from GroupedValues) b
on a.Frequency=b.MaxFrequency
答案 0 :(得分:0)
我相信你只是这样做:
select top 1
Value
from (
select
Table1.Cost, Table2.AccountNumber
Count(*) as Frequency,
Table1.Cost as Value
from Table1 cross join Table2
group by Table1.Cost, Table2.AccountNumber, Table1.Cost
) T
order by
Frequency desc,
Value desc