Cod*_*nja 32 sql t-sql sql-server sql-server-2008
我有两个查询:查询简化,不包括联接
Query 1 : select ProductName,NumberofProducts (in inventory) from Table1.....;
Query 2 : select ProductName, NumberofProductssold from Table2......;
Run Code Online (Sandbox Code Playgroud)
我想知道如何获得输出:
ProductName NumberofProducts(in inventory) ProductName NumberofProductsSold
Run Code Online (Sandbox Code Playgroud)
用于获取每个查询的输出的关系是不同的.我需要以这种方式输出我的SSRS报告.
(我尝试了union语句,但它对我想看到的输出不起作用.)
Goj*_*tah 52
下面是一个在两个完全不相关的表之间建立联合的示例:Student和Products表.它生成一个4列的输出:
select
FirstName as Column1,
LastName as Column2,
email as Column3,
null as Column4
from
Student
union
select
ProductName as Column1,
QuantityPerUnit as Column2,
null as Column3,
UnitsInStock as Column4
from
Products
Run Code Online (Sandbox Code Playgroud)
显然你会为自己的环境调整一下......
Kaf*_*Kaf 30
我想你是在追求这样的事情; (使用row_number()带有CTE和执行FULL OUTER JOIN)
;with t1 as (
select col1,col2, row_number() over (order by col1) rn
from table1
),
t2 as (
select col3,col4, row_number() over (order by col3) rn
from table2
)
select col1,col2,col3,col4
from t1 full outer join t2 on t1.rn = t2.rn
Run Code Online (Sandbox Code Playgroud)
表格和数据:
create table table1 (col1 int, col2 int)
create table table2 (col3 int, col4 int)
insert into table1 values
(1,2),(3,4)
insert into table2 values
(10,11),(30,40),(50,60)
Run Code Online (Sandbox Code Playgroud)
结果:
| COL1 | COL2 | COL3 | COL4 |
---------------------------------
| 1 | 2 | 10 | 11 |
| 3 | 4 | 30 | 40 |
| (null) | (null) | 50 | 60 |
Run Code Online (Sandbox Code Playgroud)
Jod*_*ell 12
怎么样,
select
col1,
col2,
null col3,
null col4
from Table1
union all
select
null col1,
null col2,
col4 col3,
col5 col4
from Table2;
Run Code Online (Sandbox Code Playgroud)
如果您的意思是两个ProductName字段具有相同的值,那么:
SELECT a.ProductName,a.NumberofProducts,b.ProductName,b.NumberofProductsSold FROM Table1 a, Table2 b WHERE a.ProductName=b.ProductName;
Run Code Online (Sandbox Code Playgroud)
或者,如果您希望该ProductName列仅显示一次,
SELECT a.ProductName,a.NumberofProducts,b.NumberofProductsSold FROM Table1 a, Table2 b WHERE a.ProductName=b.ProductName;
Run Code Online (Sandbox Code Playgroud)
否则,如果 Table1 的任何行可以与 Table2 中的任何行关联(尽管我真的想知道为什么有人想要这样做),您可以看一下。