-2

Hi i have a view that contains this:

sku quantity price discount
123   4       10     YES
123   1       10     YES
123   1       10     NO

the table have a lot of fields thats just a example what im trying to achieve is to group the sku by refering the quantity and discount column so it will look like this:

sku quantity price discount
123   5       10     YES
123   1       10     NO

so in this case there was 5 items with discount= YES same sku but other one with same sku 123 but quantity 1 and discount= NO, how i can group or sum that to make this work?

thank you

alexistkd
  • 906
  • 2
  • 14
  • 34

1 Answers1

0

You could use window functions depending on your version of SQL Server:

Create Sample Table:

CREATE TABLE mytable (
    sku INT
    ,quantity INT
    ,price MONEY
    ,discount VARCHAR(5)
    );

insert into mytable values
(123, 4, 10, 'YES'),
(123, 1, 10, 'YES'),
(123, 1, 10, 'NO');

Query:

select distinct sku,
       sum(quantity) OVER (partition by sku,discount order by sku) as quantity,
       max(price) OVER (partition by sku,discount order by sku) as price,
       discount       
from mytable

Result:

+-----+----------+-------+----------+
| sku | quantity | price | discount |
+-----+----------+-------+----------+
| 123 |        1 |    10 | NO       |
| 123 |        5 |    10 | YES      |
+-----+----------+-------+----------+

SQL Fiddle Demo

FutbolFan
  • 13,235
  • 3
  • 23
  • 35