我在#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


我现在想要的是一个select语句,该语句提供按周分组的所有数据。结果应如下所示。

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

最佳答案

为了将数据从行转换为列,您将需要使用PIVOT函数。

您没有指定要返回的balance值,但是根据最终结果,您似乎希望最终余额是与每天的最后交易日期关联的值。如果那是不正确的,那么请阐明逻辑应该是什么。

为了获得结果,您将需要使用DATEPARTYEAR函数。这些将允许按周和年值分组。

以下查询应获取所需的结果:

select week,
  coalesce(Deposit, 0) Deposit,
  coalesce(Withdrawals, 0) Withdrawals,
  coalesce(Stake, 0) Stake,
  coalesce(Profit, 0) Profit,
  Balance,
  Year
from
(
  select datepart(week, t1.transactiondate) week,
    t1.transactiontype,
    t2.balance,
    t1.amount,
    year(t1.transactiondate) year
  from transactions t1
  cross apply
  (
    select top 1 balance
    from transactions t2
    where datepart(week, t1.transactiondate) = datepart(week,  t2.transactiondate)
      and year(t1.transactiondate) = year(t2.transactiondate)
      and t1.userid = t2.userid
    order by TransactionId desc
  ) t2
) d
pivot
(
  sum(amount)
  for transactiontype in (Deposit, Withdrawals, Stake, Profit)
) piv;


请参见SQL Fiddle with Demo。结果是:

| WEEK | DEPOSIT | WITHDRAWALS | STAKE | PROFIT | BALANCE | YEAR |
------------------------------------------------------------------
|   13 |     150 |        -700 |  -250 |   1500 |     700 | 2013 |
|   14 |       0 |           0 |  -300 |      0 |     400 | 2013 |


附带说明一下,您说一周的开始时间是星期一,可能必须使用DATEFIRST函数设置一周的第一天。

关于sql - 将表中的数据合并到一行T-SQL,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15719445/

10-11 02:58
查看更多