在两列中合并两个选择语句? [英] combine two select statement in two column?
问题描述
我有两个选择语句
1
select Start_Date
from table1 where Start_Date not in (
select End_Date
from table1)
2
select End_Date from table1
where End_Date not in (
select Start_Date
from table1
)
当我使用union时,我想在不同的列中合并两个select语句,它给我一个列并包含两个查询的结果,我希望每个查询的结果都在不同的列中,但是当我使用那样的内部联接时
i want to combine two select statement in different column when i use union all it give me one column with the result of two queries i want each query result in different column but when i use inner join like that
select a.End_Date , b.Start_Date from
( select End_Date from table1
where End_Date not in (
select Start_Date
from table1
) ) a
join
(select Start_Date
from table1 where Start_Date not in (
select End_Date
from table1)
) b
on 1=1
每条记录给我带来的结果是重复四次,这将帮助我下一步做什么?
it giving me result every record is repeating four times help me what i do next ??
推荐答案
如果每个查询仅返回1行,则可以使用:
If each of your queries returns only 1 row you can use:
SELECT
(select Start_Date
from table1 where Start_Date not in (
select End_Date
from table1)
) AS StartDate,
(select End_Date from table1
where End_Date not in (
select Start_Date
from table1)
) AS EndDate
如果查询返回的行多于1行,则必须选择其他解决方案:
If your queries return more than 1 row you have to choose a different solution:
您可以使用UNION
:
(您将在另一列中使两个查询与"NULL"不对齐)
You can use UNION
:
(You'll have the two queries misaligned with "NULL" in the other column)
(select Start_Date, Null AS EndDate
from table1 where Start_Date not in (
select End_Date
from table1)
)
UNION
(select Null As StartDate, End_Date
from table1
where End_Date not in (
select Start_Date
from table1)
)
您可以使用JOIN
如果您有一个要用作加入"的字段,则可以使用此字段;如果没有,则可以添加一个要加入的字段(但是您需要检查返回的数据以避免错误)
另外,您还必须检查哪种连接可能对您有利(内部-左侧-固定)
在示例中,我添加了一个要联接的字段并使用了内部联接:
You can use JOIN
If you have a field to use as "Join On" you can use this field, if not you can add a field to join (but you need to check data returned to avoid errors)
Also you have to check what kind of join may be good for you (Inner - Left - rigth)
In the example I add a field to join and use an Inner Join:
SELECT Start_Date, End_Date
FROM
(select 1 as InnerId, Start_Date
from table1 where Start_Date not in (
select End_Date
from table1)
) As Tab1
INNER JOIN
(select 1 as InnerId, End_Date from table1
where End_Date not in (
select Start_Date
from table1)
) AS Tab2
USING(InnerId)
这篇关于在两列中合并两个选择语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!