Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/87.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/three.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 要从两个不同表中选择的查询_Sql - Fatal编程技术网

Sql 要从两个不同表中选择的查询

Sql 要从两个不同表中选择的查询,sql,Sql,我想从两个表中进行选择,并使用此查询显示结果: CREATE TABLE Buy_Table ( buy_id int identity primary key, user_id int, amount decimal (18,2) ); go INSERT INTO Buy_Table (user_id, amount) VALUES ('1', 10), ('1', 8), ('1', 20), ('3', 1), ('2', 2); go CREATE TABLE Sell

我想从两个表中进行选择,并使用此查询显示结果:

CREATE TABLE Buy_Table 
(
 buy_id int identity primary key, 
 user_id int, 
 amount decimal (18,2)
);
go
INSERT INTO Buy_Table 
(user_id, amount)
VALUES
('1', 10),
('1', 8),
('1', 20),
('3', 1),
 ('2', 2);
go
CREATE TABLE Sell_Table 
(
 sell_id int identity primary key, 
 user_id int, 
 amount decimal (18,2)
);
 go
 INSERT INTO Sell_Table 
 (user_id, amount)
 VALUES
 ('1', 10),
 ('1', 8),
 ('1', 20),
 ('3', 3),
 ('2', 3);
 go

select 
[user_id],
'Buy' as [Type],
buy_id as [ID],
amount

from Buy_Table

union all

select
[user_id],
'Sell',
sell_id,
amount
 from Sell_Table

order by
[user_id],
 [ID],
[Type]
但是,上面的查询将像下面这样返回用户id的每一行

我想在网格中显示我的结果,如下所示:


这可以在查询本身而不是操纵网格中完成吗?Thx

这条评论太长了

是的,可以在查询中完成。不,你不想这样做。SQL查询的结果集通常被视为表。它们可以用于查询;它们有行和列

执行您想要执行的操作违反了关系数据库中表的某些原则。最重要的是,行的顺序现在很重要。在关系数据库中,表表示无序集。如果没有排序,您就不知道第二行和后续行属于何处。不得不从另一行借用信息似乎是一种不好的做法,因为事实确实如此。另一个问题是,第一列现在的含义不明确,这取决于行中是否有值

因此,这最好在应用程序层中完成,因为其目的可能是满足某些期望的输出标准。在SQL中获取此格式是一个有趣的练习,尽管实现此格式的最佳方法因数据库而异。这就是说,做一个有趣的练习并不是一个好主意