【发布时间】:2021-08-05 19:33:54
【问题描述】:
目前我已经创建了这些临时表来获得所需的输出。但是,Power BI 不允许使用临时表,因此我需要使用内部选择将这些全部放入 1 个查询中。
drop table if exists #RowNumber
Select Date, ID, ListID
, row_number() over (partition by ID order by ID) as rownum
into #RowNumber
from Table
where Date= cast(getdate()-1 as date)
group by Date, ID, ListID
order by ID
drop table if exists #1stListIDs
select ListID as FirstID, ID, Date
into #1stListIDs
from #RowNumber
where rownum = 1
drop table if exists #2ndlistids
Select ListID as SecondListID, ID, Date
into #2ndlistids
from #RowNumber
where rownum = 2
--Joins the Two Tables back together to allow the listids to be in the same row
drop table if exists #FinalTableWithTwoListIDs
select b.FirstListID, a.SecondListID, a.ID, a.Date
into #FinalTableWithTwoListIDs
from #2ndlistids a
join #1stListIDs b on a.ID= b.ID
order by ID
此代码简单明了。但是我似乎无法弄清楚使用子查询。这就是我所拥有的。它适用于 FirstListID 选择语句,但不适用于 SecondListID 部分。我相信这是因为您不能使用多个不同的外部 select 语句来引用最内部的 select 语句,但我可能是错的。
Select a.ListId as SecondListID, a.ID, a.Date
from (
select a.ListId as FirstListID, a.ID, a.Date
from (
Select Date, ID, ListId
, row_number() over (partition by ID order by ID) as rownum
from Table
where Date = cast(getdate()-1 as date)
group by Date, ID, ListId
order by ID) a
where a.rownum = 1) b
where a.rownum = 2) c
【问题讨论】:
-
partition by ID order by ID没有什么意义,它实际上是随机的,也可能是partition by ID order by (select null) -
您是否尝试过使用通用表表达式?
标签: sql sql-server-2017