1

您在下面看到的是我为我的软件制作的库存表。我需要用它做很多计算。例如,我需要 pidstk P000007(数量)的总和,其中类型为 3,1 和类型 2,4,然后我想要(类型 3+1)-(类型 2+4)的答案。我怎样才能做到这一点?对不起我的英语。不太擅长。

+--------+------------+-----+------+-----------------+
| pidstk | dateup     | qty | type | refno           |
+--------+------------+-----+------+-----------------+
| P00007 | 2013-01-31 |  50 |    4 | 000000000000004 |
| P00007 | 2013-01-03 |  24 |    4 | 000000000000005 |
| P00007 | 2013-01-22 |  40 |    4 | 000000000000006 |
| P00007 | 2013-01-22 |  40 |    4 | 000000000000007 |
| P00007 | 2013-01-22 |  14 |    4 | ref             |
| P00007 | 2013-01-22 |   8 |    1 | ref             |
| P00007 | 2013-01-22 |   3 |    2 | ref             |
| P00007 | 2013-01-22 |   2 |    3 | ref             |
| P00007 | 2013-01-22 |   1 |    3 | ref             |
| P00007 | 2013-01-23 |  10 |    4 | 000000000000008 |
| P00007 | 2013-01-23 |   2 |    4 | 000000000000008 |
| P00007 | 2013-01-23 |  40 |    4 | 000000000000008 |
| P00007 | 2013-01-23 |  40 |    4 | 000000000000008 |
| P00007 | 2013-01-24 |   1 |    4 | 000000000000009 |
| P00007 | 2013-01-31 |  40 |    4 | 000000000000010 |
+--------+------------+-----+------+-----------------+
15 rows in set (0.00 sec)
4

2 回答 2

2

你可以使用这样的东西:

SELECT
  pidstk,
  sum(case when type in (1,4) then qty else 0 end)-
  sum(case when type in (2,3) then qty else 0 end)
FROM
  yourtable
GROUP BY
  pidstk 
于 2013-01-30T15:37:06.590 回答
0

尝试这个

   SELECT
   pidstk,
  sum(case when type in (1,4) then qty else 0 end) as total_1_4 ,
  sum(case when type in (2,3) then qty else 0 end) as total_2_3,
  sum(case when type in (1,4) then qty else 0 end)- sum(case when type in (2,3) then qty else 0 end) as the_difference
  FROM stock
  GROUP BY pidstk 

演示 SQLFIDDLE

于 2013-01-30T16:01:53.630 回答