我的表
+-----------+---------+
| Date | Letter |
+-----------+---------+
| 13.02.2013| B |
| 01.03.2016| A |
| 28.12.2003| C |
| 12.01.2017| B |
| 25.04.2011| A |
+-----------+---------+
我创建了一个返回正确数据但不符合预期的查询:
SELECT * from
(
SELECT TOP 1 Date as Date1, Letter as Letter1 from TAB where
Letter = 'A'
order by Date DESC
) TAB
UNION
SELECT * from
(
SELECT TOP 1 Date as Date2, Letter as Letter2 from TAB where
Letter = 'B'
order by Datum DESC
) TAB
预期产出:
+-----------+---------+-----------+---------+
| Date1 | Letter1 | Date2 | Letter2 |
+-----------+---------+-----------+---------+
| 01.03.2016| A | 12.01.2017| B |
+-----------+---------+-----------+---------+
输出:
+-----------+---------+
| Date1 | Letter1 |
+-----------+---------+
| 01.03.2016| A |
| 12.01.2017| B |
+-----------+---------+
是否可以使用UNION获得所有预期的4行?
谢谢。
答案 0 :(得分:1)
如果我理解正确,您似乎想要列中的列表中的" A"和" B" s。这实际上不是关系输出,因为一行中的列彼此没有关系。但是,您可以使用条件聚合来完成: TOP 1日期为Date1,Letter为Letter1
select max(case when letter = 'A' then date end) as date1,
'A' as letter1,
max(case when letter = 'B' then date end) as date2,
'B' as letter2
from (select t.*,
row_number() over (partition by letter order by date desc) as seqnum
from t
where letter in ('A', 'B')
) t
group by seqnum
order by seqnum;
答案 1 :(得分:0)
尝试将第二个查询更改为(作为日期1和字母1)列必须相同
答案 2 :(得分:0)
您可以使用join
代替union all
进行两个子查询,并使用alias
答案 3 :(得分:0)
如果您需要同一行的结果,则需要连接(而不是联合),例如:
SELECT T1.Date, T1.Letter, T2.date, T2.Letter
from (
SELECT TOP 1 '1' as id, Date , Letter
from TAB
where Letter = 'A'
order by Date DESC
) T1
INNER JOIN (
SELECT TOP 1 '1' as id, Date , Letter
from TAB
where Letter = 'B'
order by Datum DESC
) T2 on T1.id = T2.id
答案 4 :(得分:0)
希望我能正确理解你的问题。
请查看以下查询。
select Date1 , Letter1 , Date2 , Letter2
from
(SELECT TOP 1 Date as Date1, Letter as Letter1 from TAB where
Letter = 'A'
order by Date DESC) a join
(
SELECT TOP 1 Date as Date2, Letter as Letter2 from TAB where
Letter = 'B'
order by Date DESC
) b;
答案 5 :(得分:0)
这不是UNION所做的。它只是将给定的两个数据集合并为一个,如您在示例中所示。您可以尝试使用此答案中的CASE:SQL - Query same column twice with different dates in where clause