2014-09-29 50 views
0

當特定的用戶支付現金,插下表中SQL:查詢客戶銷售臺賬

payments: 
description  | Amount | Date  | custid 
cash   | 2000  | 2014-9-24 | 5 
cash   | 3000  | 2014-9-26 | 5 

特定當用戶購買產品,下表中插入

orders 
Product   | qty | amount | date  | custid 
front light  | 2 | 3000 | 2014-9-22 | 5 
back light  | 2 | 2500 | 2014-9-22 | 5 
  • 還指導我如果上面的表格需要改變。
  • 是付款表中任何需要餘額的列。 ?
  • 請記住,我是一名程序員沒有會計,如果有任何錯誤的借記卡讓我知道。

我需要這個結果或類似的東西(客戶/客戶帳戶詳細信息的銷售分類帳)。什麼是SQL查詢?

Product  | Debit | Credit  | Balance 
opening bal |  |    | 0 
product  | 5500 |    | 5500 
cash  |  | 2000   | 3500 
cash  |  | 3000   | 500 
+0

你是不是有興趣在結果中包含日期? – Strawberry 2014-09-29 10:44:50

+0

是的日期必須包括在內,並且還用在哪裏。我沒有寫在上面的表格來消除複雜性。 – 2014-09-29 10:46:23

+0

我認爲我們處理這種複雜程度。清晰度也很重要。 – Strawberry 2014-09-29 10:47:56

回答

1

首先,您沒有「open bal」的數據,所以我忽略了這一點。完全不清楚這是從哪裏來的。

獲取前三列(帶日期)是將表連接在一起的問題。爲此,union all是最好的方法:

select * 
from ((select custid, 'product' as product, date, sum(amount) as amount, -1 as dir 
     from orders 
     group by custid, date, amount 
    ) union all 
     (select custid, description, date, 1 as dir 
     from payments 
    ) 
    ) op; 

接下來是添加累計片。在MySQL中,你會這樣做使用變量:

select custid, product, date, amount, 
     (@bal := if(@c = custid, @bal + amount * dir, 
        if(@c := custid, 0, 0) 
       ) 
     ) as bal 
from ((select custid, 'product' as product, date, sum(amount) as amount, -1 as dir 
     from orders 
     group by custid, date, amount 
    ) union all 
     (select custid, description, date, amount, 1 as dir 
     from payments 
    ) 
    ) op cross join 
    (select @c := -1, @bal := 0) vars 
order by custid, date, dir desc 
+0

另外,PK應該是一個認真的考慮。 – Strawberry 2014-09-29 11:35:40

+0

#1064 - 您的SQL語法錯誤;檢查對應於你的MySQL服務器版本使用附近「作爲DIR ) UNION ALL (選擇客戶ID,DESC」在第7行 – 2014-09-29 13:28:32

+0

將在MySQL的意見這項工作嗎?如果沒有,正確的語法手冊你可以將它轉換成可以創建爲視圖的表單嗎?我只能在我的持久化類中調用表或視圖謝謝! – 2016-05-11 07:32:08