Sqlserver
 sql >> Teknologi Basis Data >  >> RDS >> Sqlserver

Permintaan untuk menampilkan kredit yang dihabiskan dari tabel transaksi

coba ini:

WITH Credits_added AS (
    SELECT CreditLogId, OccurredOn, credits
    , SUM(credits) OVER (ORDER BY CreditLogId) - credits AS b --before
    , SUM(credits) OVER (ORDER BY CreditLogId) AS a --after
    , GivenByUserCode
    FROM @CreditLogs
    WHERE Credits > 0)
, Credits_spent AS (
    SELECT CreditLogId, OccurredOn, credits
    , SUM(credits) OVER (ORDER BY CreditLogId) * -1 + credits AS b
    , SUM(credits) OVER (ORDER BY CreditLogId) * -1 AS a
    FROM @CreditLogs
    WHERE Credits < 0)
SELECT s.CreditLogId, s.OccurredOn
, CASE WHEN a.a > s.a THEN s.a ELSE a.a END - CASE WHEN a.b > s.b THEN a.b ELSE s.b END AS Credits 
, a.GivenByUserCode
FROM Credits_added AS a
INNER JOIN Credits_spent AS s ON a.a > s.b AND s.a > a.b


  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. SQL Server 2012:Pilih Top n berdasarkan beberapa kriteria

  2. Pulihkan Basis Data Dari Mode Darurat di SQL Server

  3. Apakah mungkin untuk menanyakan nama kolom yang ditentukan pengguna tanpa menggunakan SQL dinamis?

  4. InvalidCastException berkala dan Server gagal melanjutkan transaksi dengan Linq

  5. SQL Tambahkan kunci asing ke kolom yang ada