1

假设下表:

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 = Yes 的每个子公司的最高 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. 子查询本身按预期工作。感谢到目前为止的回复,但到目前为止我还没有成功地让它工作。

4

4 回答 4

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
于 2012-08-31T09:33:55.187 回答
0
SELECT SUM(NR_LIVES) 
from(
SELECT SUBSIDIARY,MAX(NR_LIVES) as NR_LIVES
from <Table>
where  FACTOR_CALC='YES'
group by SUBSIDIARY)a
于 2012-08-31T09:34:13.933 回答
0

我建议您包含一些别名,以查看这是否有助于消除 db 引擎的混淆。

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
于 2012-08-31T15:21:13.367 回答
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);
于 2012-09-01T22:40:21.290 回答