SQL Server:根据条件

时间:2017-07-07 14:21:51

标签: sql sql-server conditional select-query

我的表看起来像这样(我在能源公司工作)

dte             hub            Peak            Offpeak
07-04-2017      SoCo           36.19           18.23
07-04-2017      SwapBID        0.5             0.25
07-05-2017      SoCo           32.12           21.72
07-05-2017      SwapBID        0.25            0.25
07-06-2017      SoCo           33.87           20.34
07-06-2017      SwapBID        0.5             0.5 

我希望能够使用选择查询从此表中提取数据,并使其在同一天内将两个集线器的峰值和非峰值价格相加。例如,在2017年4月7日那天,我希望它显示峰值为36.69,而Offpeak为18.48。我想在桌子上每天都这样做。我该如何编码?

2 个答案:

答案 0 :(得分:1)

只需按日期汇总您的表格,并将峰值和非峰值值相加:

SELECT
    dte,
    SUM(Peak) AS Peak,
    SUM(Offpeak) AS Offpeak
FROM yourTable
GROUP BY dte

如果给定日期可能有多个hub类型,但我们只想考虑SoCoSwapBID个中心,那么我们可以考虑添加WHERE子句查询:

WHERE hub IN ('SoCo', 'SwapBID')

答案 1 :(得分:0)

您正在寻找汇总group by

尝试:

create table #t(dte date,hub varchar(100),Peak float,Offpeak float)
insert into #t values
('07-04-2017','SoCo',36.19,18.23),
('07-04-2017', 'SwapBID',0.5,0.25),
('07-05-2017','SoCo',32.12,21.72),
('07-05-2017','SwapBID',0.25,0.25),
('07-06-2017', 'SoCo,33.87,20.34),
('07-06-2017', 'SwapBID',0.5,0.5 )

select dte,
sum(Peak) as total_peak,
sum(Offpeak) as total_offpeak
 from #t
group by dte