SQL-使用条件从查询结果分配多个变量

时间:2018-10-04 09:11:37

标签: sql tsql

假设查询

SELECT RecordType, COUNT(*) RecordsCount FROM Records AS WHERE ... GROUP BY RecordType返回此表:

------------------------------
|RecordType   | RecordsCount |
------------------------------
|      1       |    15       |
------------------------------
|      2       |    10       |
------------------------------
|      3       |    8        |
------------------------------

我已经定义了这些变量:

DECLARE @paymentRecordCount INT = 0;
DECLARE @dataRecordCount INT = 0;

我正在寻找一种方法,一次设置 两个变量-@paymentRecordCount变量为条件where RecordType = 1的结果,并设置{{1 }}转换为条件@dataRecordCount的结果。

到目前为止,我发现的唯一方法是多次计算选择查询,如下所示: where RecordType = 3 并对其他变量执行相同的操作,例如:  select @dataRecordCount = RecordsCount from (select ... from ..) where RecordType = 3

有一种方法可以只计算一次查询并将两个变量设置在一起?

2 个答案:

答案 0 :(得分:2)

SELECT
    @paymentRecordCount = SUM(CASE WHEN RecordType = 1 THEN 1 END),
    @dataRecordCount    = SUM(CASE WHEN RecordType = 3 THEN 1 END)
FROM
    Records
WHERE
    ... 
    AND RecordType IN (1, 3)

答案 1 :(得分:0)

您可以对每个RecordType使用一个带有一个子查询的语句,但必须考虑以下情况:每个RecordType有多个值:

declare @table Table (recordtype int, recordscount int)
insert @table values (1, 1);
declare @dataRecordCount int, @paymentRecordCount int;

SELECT
@paymentRecordCount = (SELECT RecordsCount FROM @table WHERE RecordType=1),
@dataRecordCount = (SELECT RecordsCount FROM @table WHERE RecordType=3);


SELECT @dataRecordCount, @paymentRecordCount;