SQL Server 在一次选择中分配多个变量

mpgws1up  于 2022-12-28  发布在  其他
关注(0)|答案(1)|浏览(174)

我有以下疑问:

SELECT
    ROW_NUMBER() OVER(ORDER BY A.Price) AS R,
    A.Price
FROM 
    TableA A
INNER JOIN 
    TableB B ON A.ID = B.ID
INNER JOIN 
    TableC C ON C.Code = A.Code
WHERE
    C.Type = 125
    AND A.Desc = 10000038
    AND C.YearID = 10000021
GROUP BY 
    A.Price

此查询返回
| 右|价格|
| - ------| - ------|
| 1个|一百六十五|
| 第二章|四八七|
| 三个|小行星1807|
是否可以在一次选择中分配变量@a = 165、@b = 487和@c = 1807?
我写了这个查询:

WITH P AS (
SELECT
    ROW_NUMBER() OVER(ORDER BY A.Price) AS R,
    A.Price
FROM 
    TableA A
INNER JOIN 
    TableB B ON A.ID = B.ID
INNER JOIN 
    TableC C ON C.Code = A.Code
WHERE
    C.Type = 125
    AND A.Desc = 10000038
    AND C.YearID = 10000021
GROUP BY 
    A.Price
)
SELECT
    @a = (CASE WHEN [R] = 1 THEN P.[Price] END),
    @b = (CASE WHEN [R] = 2 THEN P.[Price] END),
    @c = (CASE WHEN [R] = 3 THEN P.[Price] END)
FROM P;

但是只有@c得到这个值。

58wvjzkj

58wvjzkj1#

您需要进行聚合。您的查询返回3行,这意味着变量也被赋值了 *3次 *。其顺序也是任意的,但可能是@a首先被赋值165,然后是NULL,然后是NULL
如果进行聚合,则可以返回 * 一 * 行,然后分配将按预期工作;其中每个变量被赋予1个值(而不是3个):

SELECT @a = MAX(CASE WHEN [R] = 1 THEN P.[Price] END),
       @b = MAX(CASE WHEN [R] = 2 THEN P.[Price] END),
       @c = MAX(CASE WHEN [R] = 3 THEN P.[Price] END)
FROM P;

相关问题