假设下表:
ID COMPANY SUBSIDIARY NR_LIVES INSURANCE_LINE FACTOR_CALC
1 COMPANY_X SUB_1 860 LIFE YES
2 COMPANY_X SUB_1 860 DISABILITY YES
3 COMPANY_X SUB_1 860 MEDICAL YES
4 COMPANY_X SUB_2 46 LIFE YES
5 COMPANY_X SUB_2 689 MEDICAL YES
6 COMPANY_X SUB_3 852 LIFE YES
我需要一个返回值为2401的SQL字符串。 这是通过在FACTOR_CALC =是的情况下使每个子公司的最高NR_Of_Lives之和来完成的。 我可能会知道如何在记录集中加载所有内容然后使用VBA,但如果可以在一个SQL命令中使用它,我将不胜感激。
更新: 当前查询:
sSQL_Select = "SELECT SUM(NR_LIVES) FROM (SELECT SUBSIDIARY, MAX(NR_LIVES) FROM T_WILMA WHERE PARENT=" & lParent & " AND ACC_YEAR=" & lAcc_Year & _
" AND FACTOR_CALCULATION=TRUE GROUP BY SUBSIDIARY);"
抛出错误:参数太少,预期为1。 子查询本身按预期工作。 感谢到目前为止的答复,但到目前为止我还没有成功。
答案 0 :(得分:1)
您可以确定子查询中每个子公司的最大值。外部查询可以将最大值相加。
select sum(MaxLives)
from (
select company
, subsidiary
, max(nr_lives) as MaxLives
from YourTable
where factor_calc = 'yes'
group by
company
, subsidiary
) as SubQueryAlias
答案 1 :(得分:0)
SELECT SUM(NR_LIVES)
from(
SELECT SUBSIDIARY,MAX(NR_LIVES) as NR_LIVES
from <Table>
where FACTOR_CALC='YES'
group by SUBSIDIARY)a
答案 2 :(得分:0)
我建议你加入一些别名来查看是否有助于解除对数据库引擎的干扰。
sSQL_Select = "SELECT SUM(sub.MaxOfNR_LIVES) AS NR_LIVES" & vbcrlf & _
"FROM (" & vbCrLf & _
"SELECT SUBSIDIARY, MAX(NR_LIVES) AS MaxOfNR_LIVES" & vbCrLf & _
"FROM T_WILMA WHERE PARENT=" & lParent & _
" AND ACC_YEAR=" & lAcc_Year & _
" AND FACTOR_CALCULATION=TRUE GROUP BY SUBSIDIARY) AS sub;"
Debug.Print sSQL_Select
答案 3 :(得分:0)
您需要让系统知道它正在尝试添加的NR_LIVES。在你的桌子上(并取出WHERE
中不在你的例子中的额外内容,这将返回2401
SELECT Sum(MAXNR_LIVES) AS Expr1
FROM (SELECT SUBSIDIARY, MAX(NR_LIVES) AS MAXNR_LIVES FROM T_WILMA
WHERE FACTOR_CALC=TRUE GROUP BY SUBSIDIARY);