各位先進:
小弟有一個MSSQL資料庫問題,在爬文後找不到相同的解法,
請教各位解決小弟的問題,感恩!
庫存異動明細
============
料號|庫別 |進出別 |數量
===|====|======|====
01 |T1 | 1 | 10
02 |T1 | 1 | 5
01 |T1 | 1 | 10
02 |T1 | -1 | 3
03 |T2 | 1 | 20
01 |T1 | -1 | 15
select sum(數量) from ST where 料號='01' and 庫別='T1' and 進出別='1'
結果:
數量20
select sum(數量) from ST where 料號='01' and 庫別='T1' and 進出別='-1'
結果:
數量15
如何一個直接語法,將進出別為'1'的數量, 減去進出別'-1'的數量
希望結果列出為5(庫存餘數)
<pre class="c" name="code">CREATE TABLE ithelp040401(
partno CHAR(2) NOT NULL,
dept CHAR(2) NOT NULL,
diff TINYINT NOT NULL,
qty TINYINT NOT NULL
);
INSERT INTO ithelp040401(partno, dept, diff, qty) VALUES
('01', 'T1', 1, 10),
('02', 'T1', 1, 5),
('01', 'T1', 1, 10),
('02', 'T1', -1, 3),
('03', 'T2', 1, 20),
('01', 'T1', -1, 15);
SELECT SUM(diff * qty)
FROM ithelp040401
WHERE partno = '01'
AND dept = 'T1';
+-----------------+
| SUM(diff * qty) |
+-----------------+
| 5 |
+-----------------+
我原本還在心裡犯嘀咕
什麼 1 什麼 -1 的
搞的我好亂呀
原來是這麼用來的
結果沒想到
那個欄位的資料型態是文字
<pre class="c" name="code">CREATE TABLE ithelp040401b(
partno CHAR(2) NOT NULL,
dept CHAR(2) NOT NULL,
diff CHAR(2) NOT NULL,
qty TINYINT NOT NULL
);
INSERT INTO ithelp040401b(partno, dept, diff, qty) VALUES
('01', 'T1', '1', 10),
('02', 'T1', '1', 5),
('01', 'T1', '1', 10),
('02', 'T1', '-1', 3),
('03', 'T2', '1', 20),
('01', 'T1', '-1', 15);
SELECT SUM(CAST(diff AS SIGNED) * qty) AS 'Ans'
FROM ithelp040401b
WHERE partno = '01'
AND dept = 'T1';
+------+
| Ans |
+------+
| 5 |
+------+
文字型態可以透過型別轉換.
hitomitanaka提到:
文字型態可以透過型別轉換