我需要的是存储过程,根据3个表格给出了以下结果:
我拥有的是:
表1:TBL_USER
userid Client_name
------ --------
2101 client 1
2102 client 2
2105 client 3
2106 client 4
表2:账户余额
Acbc_UserID Acbc_Remained
----------- -------------
2101 2.32
2102 2.727
2105 223.783
2106 26.77
表3 = opper_price
Opprice_UserID Opprice_Price
------- -------
2101 0.008
2101 0.008
2101 0.008
2101 0.008
2102 0.009
2102 0.009
2102 0.009
2102 0.009
2105 0.009
2105 0.009
2105 0.009
2105 0.009
2106 0.010
2106 0.010
2106 0.010
2106 0.010
(这里我们需要一个平均值,例如user_id 2106
有4个价格,所以我们需要得到平均值,这又是0.009)
根据上表,我想得到以下结果:
如果表3中不存在用户ID,则使用0.006的平均价格
Client_Name average_price Acbc_Remained SMS_remain
Client 1 0.008 2.32 ( Acbc_Remained /average_price)
Client 2 0.009 2.727 (2.727/0.009=303)
Client 3 0.009 223.783 24864.7778
Client 4 0.010 26.77 2677
========
Total of column SMS_remain
所以我想要做的就是拥有这个存储过程并将其添加到SQL Server电子邮件中,这样整个结果表也将被发送。
这是我到目前为止所做的,但价格为NULL:
BEGIN
SET NOCOUNT ON;
SELECT Prj_Users.Users_ID
,Prj_Users.Users_Name AS prj_users
,Prj_AccountBalance.Acbc_Remained AS Prj_AccountBalance
,Prj_OpperPrice.Opprice_Price AS Price
FROM Prj_Users LEFT JOIN Prj_AccountBalance
ON Prj_Users.Users_ID = Prj_AccountBalance.Acbc_UserID
LEFT JOIN Prj_OpperPrice
ON Prj_OpperPrice.Opprice_UserID = Prj_OpperPrice.Opprice_Price
END
谢谢
答案 0 :(得分:0)
Select Client_Name
,average_price = avg(Opprice_Price)
,Acbc_Remaind = avg(Acbc_Remained)
,SMS_Remain = case when avg(Opprice_Price)=0 then 0 else avg(Acbc_Remained)/avg(Opprice_Price) end
From TBL_User A
Join opper_price B on (A.userid=B.Opprice_UserID)
Join Accountbalance C on (A.userid=C.Acbc_UserID)
Group By Client_Name
返回
Client_Name average_price Acbc_Remaind SMS_Remain
client 1 0.008 2.32 290.00
client 2 0.009 2.727 303.00
client 3 0.009 223.783 24864.7777
client 4 0.01 26.77 2677.00
这一项包括总计并减少冗余计算:
Select A.*
,SMS_Remain = case when average_price=0 then 0 else Acbc_Remaind/average_price end
,Total_SMS_Remain =SUM(case when average_price=0 then 0 else Acbc_Remaind/average_price end) OVER ()
From (
Select Client_Name
,average_price = isnull(avg(Opprice_Price),.006)
,Acbc_Remaind = isnull(avg(Acbc_Remained),0)
From @TBL_User A
Left Join @opper_price B on (A.userid=B.Opprice_UserID)
Left Join @Accountbalance C on (A.userid=C.Acbc_UserID)
Group By Client_Name
) A
返回
Client_Name average_price Acbc_Remaind SMS_Remain Total_SMS_Remain
client 1 0.008 2.32 290.00 28134.7777
client 2 0.009 2.727 303.00 28134.7777
client 3 0.009 223.783 24864.7777 28134.7777
client 4 0.01 26.77 2677.00 28134.7777
client 5 0.006 0.00 0.00 28134.7777
关于客户端5的注意事项.0006和Acbc_Remaind上的0这是通过使用ISNULL()函数完成的