Author |
Topic |
JMAIL
Starting Member
2 Posts |
Posted - 2014-01-21 : 12:20:34
|
I have following situation:table_1pid discount1 82 73 9table_2pid name price 1 aa 11 1 aa 12 1 aa 13 1 aa 10 2 bb 22 2 bb 33 3 cc 66 I need a query which will generate this result:pid name price discount1 aa 11 81 aa 12 01 aa 13 01 aa 10 02 bb 22 72 bb 33 03 cc 66 9any help? |
|
tkizer
Almighty SQL Goddess
38200 Posts |
Posted - 2014-01-21 : 13:46:58
|
Could you explain words the result set?Tara KizerSQL Server MVP since 2007http://weblogs.sqlteam.com/tarad/ |
|
|
Lamprey
Master Smack Fu Yak Hacker
4614 Posts |
Posted - 2014-01-21 : 14:05:46
|
I know I shouldn't guess, but I'm gunna anyway.. :)DECLARE @table_1 TABLE (pid int, discount int)INSERT @table_1 VALUES(1, 8),(2, 7),(3, 9)DECLARE @table_2 TABLE (pid int, name varchar(20), price int)INSERT @table_2 VALUES(1, 'aa', 11), (1, 'aa', 12), (1, 'aa', 13), (1, 'aa', 10), (2, 'bb', 22), (2, 'bb', 33), (3, 'cc', 66)SELECT pid, name, Price, CASE WHEN RowNum = 1 THEN discount ELSE 0 END AS discountFROM ( SELECT B.pid, B.name, B.Price, A.Discount, ROW_NUMBER() OVER (PARTITION BY B.pid ORDER BY price DESC) AS RowNum FROM @table_1 AS A INNER JOIN @table_2 AS B ON A.pid = B.pid ) AS T |
|
|
JMAIL
Starting Member
2 Posts |
Posted - 2014-01-21 : 18:26:37
|
Thanks Lamprey, you just save my day.quote: Originally posted by Lamprey I know I shouldn't guess, but I'm gunna anyway.. :)DECLARE @table_1 TABLE (pid int, discount int)INSERT @table_1 VALUES(1, 8),(2, 7),(3, 9)DECLARE @table_2 TABLE (pid int, name varchar(20), price int)INSERT @table_2 VALUES(1, 'aa', 11), (1, 'aa', 12), (1, 'aa', 13), (1, 'aa', 10), (2, 'bb', 22), (2, 'bb', 33), (3, 'cc', 66)SELECT pid, name, Price, CASE WHEN RowNum = 1 THEN discount ELSE 0 END AS discountFROM ( SELECT B.pid, B.name, B.Price, A.Discount, ROW_NUMBER() OVER (PARTITION BY B.pid ORDER BY price DESC) AS RowNum FROM @table_1 AS A INNER JOIN @table_2 AS B ON A.pid = B.pid ) AS T
|
|
|
|
|
|