在 SQL 服务器中重新创建 For 循环?

Recreating a For Loop in SQL Server?

我正在尝试在 SQL 中重新创建一个 for 循环。我有一个 table,其中包含公司 ID、公司名称、财政年度、财政季度和各种数据项等字段。对于每个数据项 ID,我需要获取所有公司的数据项值和 select 具有最大财政年度和最大财政季度的行。例如,如果这是我的样本 table:

Company ID | Fiscal Year | Fiscal Quarter | DataItemID | DataItem Value 
1          | 2018        | 1              | 100        | 0,000  
1          | 2018        | 3              | 100        | 0,000
1          | 2017        | 4              | 200        | 35.5 
2          | 2017        | 4              | 100        | 0,000 
2          | 2018        | 1              | 200        | 40.0
2          | 2016        | 2              | 100        | 0,000 
2          | 2017        | 3              | 200        | 50.5

我的输出应该是:

Company ID | Fiscal Year | Fiscal Quarter | DataItemID | DataItem Value  
1          | 2018        | 3              | 100        | 0,000
1          | 2017        | 4              | 200        | 35.5 
2          | 2017        | 4              | 100        | 0,000 
2          | 2018        | 1              | 200        | 40.0    

因此,对于每个数据项 ID,遍历所有公司和 select 每个公司具有最大财政年度和财政季度的行以及数据项值。

我有以下部分有效的代码。对于一个 DataItemID,它工作得很好。然而,对于多个数据项,它并没有遍历所有公司。

SELECT top (1) with ties companyid, COMPANYName, dataitemname, fiscalyear,fiscalquarter, periodtypeid, dataitemvalue As Data_Value

    FROM dbo.ciqCompany  
    -- List out dataitems to report  
  WHERE dataItemID IN (100,200)

    order by row_number() over (partition by companyId order by fiscalyear desc, fiscalquarter desc)

我认为问题在于 Where 子句“WHERE dataItemID IN (100,200)”。由于这是一个 "OR" 条件,它不会选取每个 ID 的所有记录。对此有任何想法将不胜感激!非常感谢!

您还需要 partition 子句 DataItemID

. . .
row_number() over (partition by companyId, DataItemID order by fiscalyear desc, fiscalquarter desc)

您只需添加一个额外的分区即可包含 DataItemID

 order by row_number() over (partition by companyId, DataItemID order by fiscalyear desc, fiscalquarter desc)