我有一个问题,我的SQL查询我也写了。很久以前,因为我写了一个查询,所以我可以使用我的一些帮助。我试过寻找例子,但没有找到正确的结果。我写了一个查询,但它真的不适合我.. 我想要做的是获取数据库中每个日期的总功耗之和。 我的表看起来像:
|HistoryProbes|
|-------------|
|id (int) pk |
|timestamp (datetime) formatted as: "yyyy-MM-ddTHH:mm:ss"|
|PowerConsumption (int)|
我找到了一个做得很好的样品..但它不是我最好的解决方案.. 它可以在http://cephas.net/blog/2005/12/06/sql-server-group-by-datetime/
找到到目前为止,我有这个工作
SELECT distinct CONVERT(varchar, timestamp, 111) AS thedate
FROM HistoryProbes
我得到了价值25/11/2009和24/11/2009,但我无法获得PowerConsumption的总和
感谢。
答案 0 :(得分:3)
select CONVERT(varchar, timestamp, 111) as timestamp_by_day
, sum(PowerConsumption) as total_power
from HistoryProbes
group by CONVERT(varchar, timestamp, 111)
order by CONVERT(varchar, timestamp, 111)
答案 1 :(得分:3)
这样的事情会给你每天的总和
DECLARE @HistoryProbes TABLE(
id INT,
timesmp DATETIME,
PowerConsumption INT
)
INSERT INTO @HistoryProbes (id,timesmp,PowerConsumption) SELECT 1, '01 Jan 2009 12:00:00',1
INSERT INTO @HistoryProbes (id,timesmp,PowerConsumption) SELECT 2, '01 Jan 2009 11:00:00',2
INSERT INTO @HistoryProbes (id,timesmp,PowerConsumption) SELECT 3, '01 Jan 2009 13:00:00',3
INSERT INTO @HistoryProbes (id,timesmp,PowerConsumption) SELECT 4, '01 Jan 2009 14:00:00',4
INSERT INTO @HistoryProbes (id,timesmp,PowerConsumption) SELECT 5, '02 Jan 2009 12:00:00',14
INSERT INTO @HistoryProbes (id,timesmp,PowerConsumption) SELECT 6, '02 Jan 2009 11:00:00',24
INSERT INTO @HistoryProbes (id,timesmp,PowerConsumption) SELECT 7, '03 Jan 2009 13:00:00',34
INSERT INTO @HistoryProbes (id,timesmp,PowerConsumption) SELECT 8, '03 Jan 2009 14:00:00',44
SELECT DATEADD(dd,0, DATEDIFF(dd,0,timesmp)),
SUM(PowerConsumption)
FROM @HistoryProbes
GROUP BY DATEADD(dd,0, DATEDIFF(dd,0,timesmp))
答案 2 :(得分:1)
试试这个:
SELECT Convert(varchar, timestamp, 111) as thedate, SUM(PowerConsumption) as Total
FROM HistoryProbes
GROUP BY Convert(varchar, timestamp, 111)
我不确定为什么你需要在那里分明;因为你没有加入任何其他表