将这些临时表变成一个更长的子查询(不能在 Power BI 中使用临时表)

Turn these temp tables into one longer subquery (can't use Temp tables in Power BI)

目前我已经创建了这些临时表以获得所需的输出。但是,Power BI 不允许使用临时表,因此我需要使用内部 selects.

将其全部放入 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 select 语句,但不适用于 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

您可以使用 CTE 并将两者连接在一起来完成,但这样做效率低下且没有必要。

看来你只需要LAG就可以得到之前的ListID

I note that PARTITION BY ID ORDER BY ID is non-deterministic and the ordering will be random. I strongly suggest you find a deterministic ordering.

SELECT
  PrevID AS b.FirstListID,
  ListID AS a.SecondListID,
  ID,
  Date
FROM (
    SELECT
      Date,
      ID,
      ListID,
      ROW_NUMBER() OVER (PARTITION BY ID ORDER BY ID) AS rownum,
      LAG(ListID) OVER (PARTITION BY ID ORDER BY ID) AS PrevID
    from [Table]
    where Date = cast(getdate() - 1 as date)
    group by Date, ID, ListID 
) AS WithRowAndLag
WHERE rownum = 2;
ORDER BY ID;

为了完整起见,只是为了展示如何使用 CTE 替换 #temp tables,这将类似于

with RowNumber as (
    select Date, ID, ListID 
    , row_number() over (partition by ID order by ID) as rownum
    from Table
    where Date= cast(dateadd(day,-1,getdate()) as date)
    group by Date, ID, ListID 
),
FirstListIDs as (
    select ListID as FirstID, ID, Date
    from RowNumber
    where rownum = 1
),
SecondListIDs as (
    select ListID as SecondID, ID, Date
    from RowNumber 
where rownum = 2
)

select f.FirstID, s.SecondID, s.ID, s.Date
from Secondlistids s
join FirstListIDs f on s.ID=f.ID
order by s.ID

请注意 dateadd 的使用,建议在模棱两可的 date +/- value assumed to be days 和相关的 有意义的 table 别名中使用。