如何总结每周数字列中的值?

时间:2017-12-19 07:31:05

标签: sql-server tsql

我需要为每个WeekNumber的Money列总结值。

现在我有了观点:

WeekNumber  |   DayTime    |   Money 
---------------------------------------
1           |   2012-01-01 |    20.4
1           |   2012-01-02 |    30.5
1           |   2012-01-03 |    55.1
2           |   2012-02-01 |    67.3
2           |   2012-02-02 |    33.4
3           |   2012-03-01 |    11.8
3           |   2012-03-04 |    23.9
3           |   2012-03-05 |    34.3
4           |   2012-04-01 |    76.6
4           |   2012-04-02 |    90.3

Tsql:

SELECT datepart(week,DayTime) AS WeekNumber, DayTime, Money FROM dbo.Transactions

总之,我想得到这样的结论:

WeekNumber  |   DayTime    |    Sum
---------------------------------------
1           |   2012-01-01 |    106
2           |   2012-02-02 |    100.7
3           |   2012-03-03 |    470
4           |   2012-04-01 |    166.9

每个周数的DayTime应该是随机的,但是在上面的视图中的DayTime列中。

请随意写下您的想法。谢谢。

4 个答案:

答案 0 :(得分:1)

试试这个

SELECT datepart(week,DayTime) AS WeekNumber, SUM(Money) FROM dbo.Transactions GROUP BY WeekNumber

由于每周都有行数,因此无法使用同一个表获取DayTime。还有其他方法可以添加JOIN

答案 1 :(得分:1)

SELECT datepart(week,DayTime) AS WeekNumber
     , MIN(DayTime) DayTime  --<-- Instead of random get first date from your data in that week
     , SUM(Money) AS [Sum] 
FROM dbo.Transactions
GROUP BY datepart(week,DayTime)

答案 2 :(得分:0)

更改您的SQL以汇总金钱列。喜欢这个

SELECT 
datepart(week,DayTime) AS WeekNumber, 
DayTime, Money = SUM(Money) 
FROM dbo.Transactions
GROUP BY datepart(week,DayTime),DayTime

答案 3 :(得分:0)

SELECT datepart(week, DayTime) AS WeekNumber
    ,MIN(DayTime)
    ,SUM(MONEY)
FROM dbo.Transactions
GROUP BY datepart(week, DayTime)