sql利用視圖實現一個數值型欄位的求和問題

來源:互聯網
上載者:User
有如下簡單需求:客戶購買產品,廠商想看到收入和欠費統計。
已存在的資料庫主要表結構:客戶表(Customer)和銷售記錄表(SoldRecord),另外相關表(如產品表Product)在此略過。
1、客戶表
這個表很簡單:

欄位說明:tid  int  自增欄位 關鍵字
name 客戶名
adddate 添加日期
address 客戶所在地

2、銷售記錄表

欄位說明:tid  int  自增欄位  關鍵字
customerid  客戶tid
boughtdate 客戶購買產品日期
paidmoney  金額(正數代表已付款,負數代表欠費)

客戶需求分析:“廠商想看到收入和欠費統計”,分析上述表結構,可以看到問題的由來就出在這個表的paidmoney欄位上。收入必須將paidmoney按照正數相加,欠費則必須按負數相加。這樣我們就想到將paidmoney欄位“拆一為二”,便於sql函數的統計計算。
3、視圖建立(viewRecordDetail)SELECT     dbo.Customer.tid, dbo.Customer.name, dbo.Customer.addDate, dbo.Customer.address, dbo.SoldRecord.boughtDate, dbo.SoldRecord.tid AS sid, 
                      ABS(CASE WHEN dbo.SoldRecord.paidMoney > 0 THEN dbo.SoldRecord.paidMoney ELSE 0 END) AS income, 
                      ABS(CASE WHEN dbo.SoldRecord.paidMoney < 0 THEN dbo.SoldRecord.paidMoney ELSE 0 END) AS outcome, dbo.SoldRecord.paidMoney
FROM         dbo.Customer INNER JOIN
                      dbo.SoldRecord ON dbo.Customer.tid = dbo.SoldRecord.CustomerId
GROUP BY dbo.Customer.tid, dbo.SoldRecord.tid, dbo.Customer.name, dbo.Customer.addDate, dbo.Customer.address, dbo.SoldRecord.boughtDate, 
                      dbo.SoldRecord.paidMoney

很明顯,兩個表的串連查詢建立一個視圖,重點是利用case when將paidmoney的拆分。其中income為收入,outcome為欠費,函數ABS取絕對值(我們當然可以利用其他函數如sum取值)。這樣需要統計的話,直接對視圖進行操作就可以了。
4、簡單樣本
下面向兩個表裡填充一些資料,測試一下。
(1)、客戶表use testdb
insert into customer select 'jeff wong',getdate(),'beijing'
union all select 'jeffery zhao',getdate(),'shanghai'
union all select 'dudu',getdate(),'shanghai'
union all select 'terrylee',getdate(),'tianjin'

(2)、銷售記錄表use testdb

insert into soldRecord select 1,getdate(),168
union all select 2 ,getdate(),223
union all select 1,getdate(),-7500
union all select 1,getdate(),268
union all select 4 ,getdate(),-113
union all select 3,getdate(),500
union all select 1,getdate(),22
union all select 4 ,getdate(),15
union all select 3,getdate(),-15000
union all select 1,getdate(),200
union all select 2 ,getdate(),111
union all select 2,getdate(),7000
union all select 2,getdate(),268

(3)、統計select sum(income) as totalIncome,
sum(outcome) as totalOutcome from viewRecordDetail

小結:這裡只是記錄一下個人解決問題的思路和簡單實踐,並不推薦直接利用sql的dbms做這些瑣碎的統計處理。sql固然強大,但是,汝之蜜糖,焉知不是我之毒藥呢?其實強大的進階語言如c#,java等都可以輕鬆實現這些功能,更何況建立太多視圖什麼的不易維護。還是千方百計地建立合理的表結構,交給進階語言處理去吧。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.