我在#SQL server 2008 中有一个包含事务数据的表。桌子看起来像这样。我想在 sql 语句中有这个。
TransactionId|TransactionDate|TransactionType|Amount|Balance|UserId
交易类型可以是存款、取款、利润和权益四种类型之一。我举一个例子,它在事务表中的样子。余额是金额总和列。
TransactionId|TransactionDate|TransactionType|Amount|Balance|UserId
1| 2013-03-25| Deposit| 150| 150| 1
2| 2013-03-27| Stake| -20| 130| 1
3| 2013-03-28| Profit | 1500| 1630| 1
4 | 2013-03-29| Withdrawals| -700| 930| 1
5| 2013-03-29| Stake | -230 | 700 | 1
6| 2013-04-04| Stake| -150 | 550| 1
7| 2013-04-06| Stake | -150 | 400| 1
我现在想要的是获得一个选择语句,它为我提供按周分组的所有数据。结果应该是这样的。
Week|Deposit|Withdrawals|Stake|Profit|Balance|Year
13 | 150| -700 | -250 | 1500 | 700 | 2013
14 | 0 | 0 | -300| 0 | 400 | 2013
我也有几周的问题......我住在欧洲,一周的第一天是星期一。我有一个解决方案,但在一年结束时我有时会得到第 54 周,但一年中只有 52 周......
我希望有人可以帮助我。
这就是我到目前为止所拥有的。
SELECT transactionid,
transactiondate,
transactiontype,
amount,
(SELECT Sum(amount)
FROM transactions AS trans_
WHERE trans_.transactiondate <= trans.transactiondate
AND userid = 1) AS Balance,
userid,
Datepart(week, transactiondate) AS Week,
Datepart(year, transactiondate) AS Year
FROM transactions trans
WHERE userid = 1
ORDER BY transactiondate DESC,
transactionid DESC
这是示例数据和我对 sql-fiddle 的查询:http ://www.sqlfiddle.com/#!3/79d65/92/0