我有一张购买表,如下所示:
Chassis_Number Customer_Trn Purchase_ID date_sold selling_price tax_amount
-------------------------------------------------------------------------------
1234 567 1234567 2012-1-23 2345653 12343
2345 678 2345678 2013-4-05 1089255 11332
另一个表 Credit_Customer ,如下所示:
Customer_Trn Repayment Monthly_Payment
----------------------------------------
567 456530 4530
我正在尝试创建一个交易来计算与月份相关的credit_customer购买(date_sold)
如果credit_customer购买< 12 /月,则允许插入其他回滚
Begin Transaction CC_Limit
Alter Table Purchases
ADD mon int
Update Purchases
Set mon = MONTH(date_sold)
Where mon IS NULL
Select Credit_Customer.Customer_Trn, Purchases.date_sold
From Credit_Customer
Inner Join Purchases
On Credit_Customer.Customer_Trn=Purchases.Customer_Trn
Order By Credit_Customer
Declare @count int = (Select Count(*) from Credit_Customer)
If @count<100
Insert into Purchases (Chassis_Number,Customer_Trn,Purchase_ID,date_sold,selling_price,tax_amount)
Values (@Chassis_Number,@Customer_Trn,@Purchase_ID,@date_sold,@selling_price,@tax_amount)
Begin
ROLLBACK trans
答案 0 :(得分:1)
如果您希望获得一个月内交易次数少于12次的所有客户,我想您想做这样的事情:
SELECT Credit_Customer, COUNT(Credit_Customer.Customer_Trn) AS Cnt, YEAR(Purchases.date_sold) AS Yr, MONTH(Purchases.date_sold) AS Mon
FROM Credit_Customer
Inner Join Purchases On Credit_Customer.Customer_Trn=Purchases.Customer_Trn
GROUP BY Yr, Mon
HAVING COUNT(*) < 12
ORDER BY Credit_Customer
答案 1 :(得分:1)
要检查信誉,您可以执行以下操作:
CREATE PROCEDURE GetCreditWorthiness
@Customer_Trn int
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE isCreditWorthy bit = 0
DECLARE @Yr = YEAR(getdate())
DECLARE @Mon = MONTH(getdate())
SELECT @isCreditWorthy = CASE WHEN COUNT(Credit_Customer.Customer_Trn) < 12 THEN 1 ELSE 0 END
FROM Credit_Customer
INNER JOIN Purchases On Credit_Customer.Customer_Trn=Purchases.Customer_Trn
WHERE Credit_Customer.Customer_Trn = @Customer_Trn
AND MONTH(date_sold) = @Mon and YEAR(date_sold) = @Yr
RETURN @isCreditWorthy
END