I am trying to find TotalPoints Sum with subtraction if new entry is made in the table,
TotalPoints Query :
SELECT SUM(t.TotalUserActions) as Actions, sum(t.AllTotalPoints) as TotalPoints,
(select Name from CustomerTable where CustomerId=1) as Name from
(
SELECT CASE
WHEN LoayaltyPointsTable.LoyaltyPointsId=4 THEN (SELECT COUNT(amount)
FROM RedeemPointsTable where CustomerId=1)
ELSE COUNT(CustomerTable.CustomerId)
END as TotalUserActions , CustomerTable.Name,
CASE
WHEN LoayaltyPointsTable.LoyaltyPointsId=4 THEN (SELECT SUM(amount)
FROM RedeemPointsTable where CustomerId=1)*Points
ELSE SUM(LoayaltyPointsTable.Points)
END as AllTotalPoints
FROM
LoayaltyPointsTable
INNER JOIN
LoyaltyDetailsTable
on LoayaltyPointsTable.LoyaltyPointsId = LoyaltyDetailsTable.LoyaltyPointsId
INNER JOIN
CustomerTable
on CustomerTable.CustomerId = LoyaltyDetailsTable.CustomerId
where CustomerTable.CustomerID =1
group by CustomerTable.Name,LoayaltyPointsTable.LoyaltyPointsId,
LoayaltyPointsTable.Points,CustomerTable.CustomerId
) t
Totalpoints Query Output:
Actions Totalpoints Name
30 500 John
PriceTable
Priceid Title Discriptions Pricepoints
1 abc abc 400
2 def def 500
PriceClaimTable
PriceClaimId CustomerId PriceId
1 1 22
2 2 23
Using above table , I am trying to subtract TotalPoints – Pricepoints based on the CustomerId and PriceId in PriceClaimTable And if there is no new entry in PriceClaimTable based on the Customerid, then just Show Totalpoints without subtraction
Thus far I tried to find the price points
select PriceTable.PricePoints from PriceTable
inner join PriceClaimTable
on PriceTable.PriceId = PriceClaimTable.PriceId
inner join CustomerTable
on CustomerTable.CustomerId = PriceClaimTable.CustomerId
where CustomerTable.CustomerId =1
group by PriceTable.PricePoints
This gives me output as:
PricePoints
400
Expected output:
TotalPoints:
100 // (500-400)
How can I subtract the results in one Query and find Total Points Sum based on customerid?
Other Table Structure:
http://sqlfiddle.com/#!2/67436/5
Any help would be great.