Click here to Skip to main content
15,893,588 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi experts,
I have a discount table looks like this:
SQL
table discount ("productId","lineNum","price","discount","toDate","fromDate")

Values could be something like this:
SQL
("product1","0","100","10","2015-03-01","2015-04-30")
("product1","1","100","10","2015-05-01","2015-06-30")

So i could have the same product with different lineNum.
What i intend to do is: select from my table all the products that have discount between 2 dates (which i could easily do). AND if the product is repeating take only the product with lineNum=1
I can't figure out this part!
EDIT: What if there is no date range? distinct won't work in this case because every line is distinct.

Any help will be so much appreciated.
Thanks in advance
Samira
Posted
Updated 29-Apr-15 6:07am
v2
Comments
CHill60 29-Apr-15 11:48am    
Try something like SELECT TOP 1 FROM discount WHERE @InDate BETWEEN toDate AND fromDate ORDER BY lineNum.
[Edit] - Nope - that won't work - sorry. Try using GROUP BY productId
Maciej Los 29-Apr-15 14:34pm    
So... in your example, the record which meet your needs is the second one. Am i right?

If i understand you correctly, you need to use ROW_NUMBER()[^] ranking function.

If lineNum starts from 0 try this:
SQL
SELECT productId , lineNum, price, discount, toDate, fromDate
FROM (
    SELECT productId , lineNum, price, discount, toDate, fromDate, ROW_NUMBER() OVER(PARTITION BY productId ORDER BY lineNum)
    FROM TableName
    WHERE fromDate >= @fromDate AND toData <= @toDate AND lineNum > 0
    ) AS T 
WHERE RowNo=1
 
Share this answer
 
Comments
Samira Radwan 29-Apr-15 15:14pm    
thanks a lot!
Maciej Los 29-Apr-15 15:23pm    
You're very welcome ;)
Sascha Lefèvre 29-Apr-15 17:32pm    
I think this query doesn't fulfill the requirement "AND if the product is repeating take only the product with lineNum=1" - because it will not return products that only have a record with lineNum=0
Maciej Los 30-Apr-15 1:43am    
Sascha, thank you for your comment, but have a look at my first [where] statement (after second [and]).
Sascha Lefèvre 30-Apr-15 20:26pm    
Please take a look here, Maciej: http://sqlfiddle.com/#!6/2f64e/1
I don't have a better solution.. can you come up with one? I would be very interested :-)
/Sascha
Try distinct
SELECT distinct productid, discount,price  FROM discount WHERE @InDate BETWEEN toDate AND fromDate ORDER BY lineNum
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900