我有两个表一个是INqty而另一个是OUTqty,我已经尝试并浏览了一个答案,但总是当我实现样本查询或者我得到重复SUM时。
Table - INqty Table - OUTqty
|ID | quantity | | ID | quantity |
|001 | 30 | | 001 | 10 |
|002 | 20 | | 002 | 10 |
|001 | 10 |
|003 | 25 |
我需要这样的结果。
|ID | Quantity IN | Quantity OUT |
|001 | 40 | 10 |
|002 | 20 | 10 |
|003 | 25 | NULL |
它与mysql 我正在使用图像中的sql,现在我只需将此结果分组并求和。
SELECT Mat_ST_IN_Sifra as IDs , SUM(Mat_ST_IN_Kol) as QTYIN , '' as QTYOUT FROM mat_stavki_in GROUP BY Mat_ST_IN_Sifra
UNION all
SELECT Mat_Stavki_Out_Sifra, '' , sum(Mat_Stavki_Out_Kolicina) FROM mat_stavki_out GROUP BY Mat_Stavki_Out_Sifra
我知道了, 感谢所有试图帮助我的人
最后我简单回答我的问题
SELECT a.IDs, sum(a.QTYIN),sum(a.QTYOUT)
FROM
(
SELECT Mat_ST_IN_Sifra as IDs , SUM(Mat_ST_IN_Kol) as QTYIN , '' as QTYOUT FROM mat_stavki_in GROUP BY Mat_ST_IN_Sifra
UNION all
SELECT Mat_Stavki_Out_Sifra, '' , sum(Mat_Stavki_Out_Kolicina) FROM mat_stavki_out GROUP BY Mat_Stavki_Out_Sifra
) as A
GROUP BY a.IDs
答案 0 :(得分:1)
考虑以下内容......
DROP TABLE IF EXISTS in_qty;
CREATE TABLE in_qty
(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, account INT NOT NULL ,quantity INT NOT NULL);
INSERT INTO in_qty (account,quantity) VALUES
(1,30),
(2,20),
(1,10),
(3,25);
DROP TABLE IF EXISTS out_qty;
CREATE TABLE out_qty
(ID INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,account INT NOT NULL,quantity INT NOT NULL);
INSERT INTO out_qty (account,quantity) VALUES
(1,10),(2,10);
SELECT account
, SUM(CASE WHEN status = 'in' THEN quantity END) `in`
, SUM(CASE WHEN status = 'out' THEN quantity END) `out`
FROM
( SELECT *,'in' status FROM in_qty
UNION ALL
SELECT *,'out' FROM out_qty
) x
GROUP
BY account;
+---------+------+------+
| account | in | out |
+---------+------+------+
| 1 | 40 | 10 |
| 2 | 20 | 10 |
| 3 | 25 | NULL |
+---------+------+------+
答案 1 :(得分:0)
尝试此查询 -
select s1.id, s1.Qin, s2.id, s2.Qout
from
(
select p.id, sum(p.qty) as Qin
from INqty as p
group by p.id
) as s1
full outer join
(
select q.id, sum(q.qty) as Qout
from OUTqty as q
group by q.id
)as s2
on s1.id = s2.id
以下是为sql server创建示例表的查询(根据您的问题):
CREATE TABLE [dbo].[OUTqty](
[id] [varchar](50) NULL,
[qty] [int] NULL
) ON [PRIMARY]
GO
INSERT [dbo].[OUTqty] ([id], [qty]) VALUES (N'001', 10)
INSERT [dbo].[OUTqty] ([id], [qty]) VALUES (N'002', 10)
GO
CREATE TABLE [dbo].[INqty](
[id] [varchar](50) NULL,
[qty] [int] NULL
) ON [PRIMARY]
GO
INSERT [dbo].[INqty] ([id], [qty]) VALUES (N'001', 30)
INSERT [dbo].[INqty] ([id], [qty]) VALUES (N'002', 20)
INSERT [dbo].[INqty] ([id], [qty]) VALUES (N'001', 10)
INSERT [dbo].[INqty] ([id], [qty]) VALUES (N'003', 25)