【问题标题】:How to find the grand total of a particular column and display it at the end?如何找到特定列的总计并在最后显示?
【发布时间】:2017-05-17 07:20:43
【问题描述】:

以下是详细信息。

date         |  Site   | Power
2017-05-11   |  ABC    | 171.123
2017-05-12   |  DEF    | 170.123
2017-05-13   |  GHI    | 172.123
2017-05-14   |  ABC    | 173.123
2017-05-15   |  DEF    | 170.123

我想计算总功率并在最后显示。

我使用的查询是

select  date, I_site,
        (
            select  sum(power) as Total_power
            from    mytable
            where   D_date between '2017-5-11' and '2017-05-15' and
                    I_site in (ABC,DEF,GHI,ABC,DEF)
        )
from    mytable
where   D_date between '3470' and '3500' and
        i_site in  (ABC,DEF,GHI,ABC,DEF)
group by date,I_site

我得到的输出是同一 Power 列中站点值的总和。

谢谢

【问题讨论】:

  • 有了那个表数据,预期的结果是什么? (此处也有格式化文本。)

标签: sql sql-server


【解决方案1】:

您的查询似乎大部分是正确的,但您不需要 group by 子句,因为您的 select 中没有聚合(sum 在内部查询中,因此不算在内)。您还缺少select 中的power 字段,这就是为什么总和将替换结果第三列中的原始power 值。

select   date, I_site, power,
         (
             select  sum(power) as Total_power
             from    mytable
             where   D_date between '2017-5-11' and '2017-05-15' and
                     I_site in ('ABC', 'DEF', 'GHI')
         )
from     mytable
where    D_date between '3470' and '3500' and
         i_site in ('ABC', 'DEF', 'GHI')

如果您在内部查询和外部查询中应用的过滤器相同,您也可以这样写

select  date, I_site, power,
        sum(power) over () as Total_power
from    mytable
where   D_date between '3470' and '3500' and
        i_site in ('ABC','DEF','GHI')

【讨论】:

    猜你喜欢
    • 2012-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多