【问题标题】:Generate sum at bottom of results在结果底部生成总和
【发布时间】:2014-07-12 02:24:33
【问题描述】:

我在 SQL Server 2005 中汇总了一个查询,按状态计算我们的体积:

SELECT ISNULL(q1.state,'UK') AS 'State', ISNULL(q1.TP,0) AS Transportation, ISNULL(q2.TL,0) AS Translation
    FROM
    (select p.state, count(Distinct t.patientID) as TP
     from v_trip t
     LEFT JOIN v_patient p ON t.patientid = p.ssn
     where t.transtype not like 'translati%'
     and created >= '5/18/2014'
     and created < '5/25/2014'
    group by p.state) AS q1
    LEFT JOIN
    (select p.state, count(Distinct t.patientID) as TL
     from v_trip t
     LEFT JOIN v_patient p ON t.patientid = p.ssn
     where t.transtype like 'translati%'
     and created >= '5/18/2014'
     and created < '5/25/2014'
    group by p.state) AS q2
    ON q1.state = q2.state
    ORDER BY q1.state

结果显示了每个州的交易量总和,我正在尝试计算总和并在我的结果底部输入。我已经尝试过ROLLUP,但它破坏了查询,可能是因为我不确定在哪里正确放置它。

【问题讨论】:

    标签: sql


    【解决方案1】:

    由于我无法弄清楚如何在查询中汇总最终输出到 CSV,因此我继续研究可能的 VB 脚本。 通过将以下几行添加到我的 VB 脚本中,我能够汇总报告的列:

    'Write header lines
    line = "Report For Week of " & (dateadd("d",-7,sDate)) & ""
    objTS.WriteLine line
    line = "State,Data1,Data2"
    objTS.WriteLine line
    
    'Write detail lines
    Do while not rs.eof
    line = rs(0) & dl & rs(1) & dl & rs(2)
    objTS.WriteLine line
    if rs(1) >= 0 then
        gtpTot = gtpTot + rs(1)
    end if
    if rs(2) >= 0 then
        gtlTot = gtlTot + rs(2)
    end if
    rs.movenext
    loop
    
    'Output grand totals
    line = "Grand Total," & gtpTot & dl & gtlTot
    objTS.WriteLine line
    

    此代码在文件末尾添加一个新行,显示我的数据的完整总数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-05-16
      • 2013-02-01
      • 1970-01-01
      • 2015-09-08
      • 2020-02-18
      • 1970-01-01
      • 2023-01-12
      相关资源
      最近更新 更多