如何找到特定列的总计并在最后显示它?

时间:2017-05-17 07:20:43

标签: sql sql-server

以下是详细信息。

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 列中网站值的总和。

谢谢

1 个答案:

答案 0 :(得分:1)

您的查询似乎大致正确,但您不需要group by条款,因为select中没有聚合(sum位于内部查询,因此不计数)。您还错过了power中的select字段,以及为什么总和正在替换结果第三列中的原始power值。<\ n / p>

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')