简体   繁体   English

sql server - for loop - 交叉应用

[英]sql server - for loop - cross apply

For the table below, I need to perform a loop operation in SQL Server 2008: 对于下表,我需要在SQL Server 2008中执行循环操作:

The column Day in the table can have values from 0 to 9. 表中的列Day可以具有0到9之间的值。

For j = 0 to 9: (Iterate through the column **Day**)
   y=0;
   For k = 0 to 9:  (Iterate through the column **Day** again)
      if x[k] >= x[j]: y= y+1;

Table A: 表A:

Key|Day| x  | y |
---|---|----|---|
123| 0 |7000|   |
123| 2 |6000|   |
123| 9 |6500|   |

I have used cross apply and got the following: 我使用交叉申请并得到以下内容:

select * from TableA A
cross apply (
select Day as k, case when B.x >= A.x then 1 else 0 end as y
from TableA B 
where A.Key = B.Key
) C

Output: 输出:

Key|Day|x[j]|k |x[k]|y |y - What I need
---|---|----|--|----|--|----------------
123|0  |7000|0 |7000|1 |1 
123|0  |7000|2 |6000|0 |1 
123|0  |7000|9 |6500|0 |1 
123|2  |6000|0 |7000|1 |1 
123|2  |6000|2 |6000|1 |2 
123|2  |6000|9 |6500|1 |3 
123|9  |6500|0 |7000|1 |1 
123|9  |6500|2 |6000|0 |1 
123|9  |6500|9 |6500|1 |2 

Not able to figure out how to get y=y+1 for every k. 无法弄清楚如何为每k获得y = y + 1。

I am not allowed to use join . 我不被允许使用join But if the performance of join is better than cross apply, please do share the solution. 但如果连接的性能优于交叉应用,请分享解决方案。

Please help. 请帮忙。 Thanks 谢谢

Edit: I tried the following to calculate running totals with the condition: 编辑:我尝试使用以下条件计算运行总计:

select * from TableA A
cross apply (
select Day as k
,sum(case when B.x >= A.x then 1 else 0 end) over (partition by A.Key,A.Day) as y
from TableA B 
where A.Key = B.Key
) C

But it doesn't give me the correct output. 但它没有给我正确的输出。 I get: 我明白了:

Key|Day|x[j]|k |x[k]|y |y - What I need
---|---|----|--|----|--|----------------
123|0  |7000|0 |7000|1 |1 
123|0  |7000|2 |6000|1 |1 
123|0  |7000|9 |6500|1 |1 
123|2  |6000|0 |7000|3 |1 
123|2  |6000|2 |6000|3 |2 
123|2  |6000|9 |6500|3 |3 
123|9  |6500|0 |7000|2 |1 
123|9  |6500|2 |6000|2 |1 
123|9  |6500|9 |6500|2 |2 

Also, when I use order by in the over clause it gives me an error: 另外,当我在over子句中使用order by时,它给出了一个错误:

The Parallel Data Warehouse (PDW) features are not enabled.

You're very close. 你很近。 I'm running SQL Server 2016. The result should be the same. 我正在运行SQL Server 2016.结果应该是相同的。 Note Key and Day column in your expected result don't match original data in TableA. 注意预期结果中的Key和Day列与TableA中的原始数据不匹配。

WITH TableY AS
(
    SELECT A.[Key], A.[Day], A.X AS xj, B.[Day] AS k, B.X AS xk, 
    (CASE WHEN B.X >= A.X THEN 1 ELSE 0 END) AS y
    FROM @TableA AS A
    INNER JOIN @TableA AS B ON A.[Key] = B.[Key]
)
SELECT *,
    SUM(y) OVER(
         PARTITION BY [Key], [Day] 
         ORDER BY k 
         ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
    ) AS 'RunningTotalY'
FROM TableY
ORDER BY [Key], [Day], xj, k;

Not sure how PDW error came from. 不确定PDW错误是如何产生的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM