iT邦幫忙

0

刪除刪除刪除刪除

  • 分享至 

  • xImage

刪除

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

4
一級屠豬士
iT邦大師 1 級 ‧ 2020-07-24 23:46:56
最佳解答
-- 增加一個製令,一個品號以及兩張採購單.
-- 比較貼近實際情況
-- 使用 MySQL 8
select version();
+-----------+
| version() |
+-----------+
| 8.0.18    |
+-----------+

create table manorder (
  ordid char(3) not null
, itemno char(5) not null
, reqamut int unsigned not null
);

insert into manorder values
('A01', 'book', 200),
('C02', 'desk', 120);

create table stock (
  itemno char(5) not null
, inventory int unsigned not null
);

insert into stock values
('book', 50),
('desk', 40);

create table purchase (
  itemno char(5) not null
, prchno char(4) not null
, qty int unsigned not null
);

insert into purchase values
('book', '0001', 50),
('book', '0002', 60),
('book', '0003', 80),
('desk', '1002', 50),
('desk', '1003', 70);

--

select ordid
     , itemno
     , reqamut
     , inventory
     , prchno
     , qty
     , sum(qty) over(partition by ordid, itemno order by prchno) as 'cumqty'
     , inventory + sum(qty) over(partition by ordid, itemno order by prchno) - reqamut as '可用量'
  from manorder m
  join stock s
 using (itemno)
  join purchase p
 using (itemno)
 ;
+-------+--------+---------+-----------+--------+-----+--------+-----------+
| ordid | itemno | reqamut | inventory | prchno | qty | cumqty | 可用量    |
+-------+--------+---------+-----------+--------+-----+--------+-----------+
| A01   | book   |     200 |        50 | 0001   |  50 |     50 |      -100 |
| A01   | book   |     200 |        50 | 0002   |  60 |    110 |       -40 |
| A01   | book   |     200 |        50 | 0003   |  80 |    190 |        40 |
| C02   | desk   |     120 |        40 | 1002   |  50 |     50 |       -30 |
| C02   | desk   |     120 |        40 | 1003   |  70 |    120 |        40 |
+-------+--------+---------+-----------+--------+-----+--------+-----------+
5 rows in set (0.03 sec)

感謝大大解答

2
REX
iT邦新手 4 級 ‧ 2020-07-25 00:54:41

MSSQL 2017
不同寫法,偷學一下屠豬大大也用兩種

SELECT O.[OrderId] '制令', P.[QNo] '品號',O.[NEEDQTY] '需用量',S.[QTY] '庫存量',P.[PurchaseId] '採購單',P.QTY '採購數量',sum(P1.QTY)+S.[QTY]-O.[NEEDQTY] '可用量' FROM  [Order] O 
LEFT JOIN [dbo].[Stock] S ON O.[QNo]=S.[QNo]
LEFT JOIN [dbo].[Purchase] P ON O.[QNo]=P.[QNo]
LEFT JOIN [dbo].[Purchase] P1 ON O.[QNo]=P1.[QNo]
WHERE   P.[PurchaseId] >= P1.[PurchaseId]
GROUP BY  O.[OrderId],P.[QNo],O.[NEEDQTY],P.[PurchaseId],S.[QTY],P.QTY
ORDER BY  O.[OrderId],P.[QNo],P.[PurchaseId]

https://ithelp.ithome.com.tw/upload/images/20200725/20110858YkNTT26ro1.png

SQL結果看這裡

很好喔.

REX iT邦新手 4 級 ‧ 2020-07-25 12:47:12 檢舉

多謝屠豬大大鼓勵/images/emoticon/emoticon12.gif

感謝大大解答

我要發表回答

立即登入回答