0

I have got a 3 table

DiscountHeader Table

 HeaderID    HeaderName
 ------------------------
 1            DiscountA

DiscountLine table

 LineID    HeaderID    Min    Max   DiscountPercentage
 -----------------------------------------------
 1         1           0      1000       1% 
 2         1           1001   2000       2%

and Branch_Totals

 CompanyID   HeaderID    Sales_Total      Discount
 ------------------------------------------------------
 B1          1              900              1%
 T2          1             1500              2%

And the Company Table

 CompanyID    HeaderID
 ------------------------
 B1            1
 T2            1

Basically, I would like to give a discount to each company according to their sell figure.

Each company has a Discount HeaderID and each Header has lines. Shows how much discount they will get. More sale, more discount.

for example, CompanyId 1, sold only 900, and they only entitled 1% because it is less than 1000. But companyID 2 sold 1500 and they are entitled 2%

So far i did this

 SELECT *
 CASE 
      WHEN B.Sales_Total >V.Min THEN 1
 END AS R
 FROM Branch_Totals B
 JOIN Company H ON H.CompanyID = B.CompanyID 
 JOIN DiscountLine V ON H.VDHeaderID = V.HeaderID

But when i said WHERE R not null. IT doesn't work.. Basically "AS R" not acceptable. I am not sure how to combine all these tables with a single query.

demo
  • 6,038
  • 19
  • 75
  • 149
AliAzra
  • 889
  • 1
  • 9
  • 28

1 Answers1

2

You can use outer apply for this:

SELECT B.*, H.*, v.discount
FROM Branch_Totals B JOIn
     Company H
     ON H.CompanyID = B.CompanyID OUTER APPLY
     (SELECT TOP (1) v.*
      FROM DiscountLine Vv
      WHERE H.VDHeaderID = V.HeaderID AND
            B.Sales_Total >= V.Min
      ORDER BY V.MIN DESC
     ) v;

I notice that you have min and max columns, so you can also just use join:

SELECT *
FROM Branch_Totals B JOIN
     Company H 
     ON H.CompanyID = B.CompanyID JOIN
     DiscountLine V
     ON H.VDHeaderID = V.HeaderID AND
        B.Sales_Total BETWEEN v.MIN and v.MAX
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786