sql server - SQL SUM() condtions questions -
i have table looks this:
+----+------+--------+----------+ | id | code | optype | quantity | +----+------+--------+----------+ | 0 | | in | 7 | | 1 | b | in | 8 | | 2 | | out | 2 | | 3 | b | in | 7 | | 4 | b | out | 12 | +----+------+--------+----------+
i want sum(quantity) depending on optype. when optype out, quantity field should multiplied -1.
the result of query should be:
code in out final 7 2 5 b 15 12 3
i've tried this, doesn't work:
select(select sum(quantity) table optype = 'in') as[in], (select sum(quantity) table optype = 'out') as[out], (select sum(quantity) table optype = 'in') - (select sum(quantity) table optype = 'out') as[final] table group code
sql server has pivot
functionality.
select [code], [in], [out], [in] - [out] [final] ( select [code], optype, sum(quantity) quantity tablename group [code], optype ) org pivot ( max(quantity) optype in ([in],[out]) ) pvt
output
╔══════╦════╦═════╦═══════╗ ║ code ║ in ║ out ║ final ║ ╠══════╬════╬═════╬═══════╣ ║ ║ 7 ║ 2 ║ 5 ║ ║ b ║ 15 ║ 12 ║ 3 ║ ╚══════╩════╩═════╩═══════╝