将虚拟/占位符数据合并到SQL查询中

时间:2019-03-25 01:13:45

标签: sql sql-server

在我们的SQL Server 2016数据库中,我们有一个Payments表,该表记录了客户每月付款的情况,但是由于他们不一定每月付款,因此我们可能缺少月份数据。

我现在需要为SSRS报告的每个客户插入丢失的每月付款数据(即零付款),因为企业希望查看报告上的每个月以评估客户的付款频率。

因此,在下面的SQL语句中,我首先创建一个表变量,并为每个月插入一行,并将付款金额设为零。然后,我创建了一些带有客户ID,付款月份和金额的示例付款数据。然后我要做的是得到一个结果,该结果为每个客户有12个条目,每个月一个,显示当月付款或0。

-- Dummy monthly payment data to use for missing months
DECLARE @DummyPayments TABLE
(
    MonthNumber INT,
    Payment MONEY
)

INSERT INTO @DummyPayments 
select 1,0 union
select 2,0 union
select 3,0 union
select 4,0 union
select 5,0 union
select 6,0 union
select 7,0 union
select 8,0 union
select 9,0 union
select 10,0 union
select 11,0 union
select 12,0

-- This (much simplified) data would come from our Payments table
DECLARE @CustomerPayments TABLE
(
    CustomerID INT,
    MonthNumber INT,
    Payment MONEY
)

-- Example customer 1 made payment in months 1,3,6,9
insert into @CustomerPayments values(1,1,100);
insert into @CustomerPayments values(1,3,120);
insert into @CustomerPayments values(1,6,140);
insert into @CustomerPayments values(1,9,95);

-- Example customer 2 made payment in months 2,5,10,12    
insert into @CustomerPayments values(2,2,80);
insert into @CustomerPayments values(2,5,90);
insert into @CustomerPayments values(2,10,130);
insert into @CustomerPayments values(2,12,105);

-- Now I want to join real payments with dummy/missing payments
-- to get payment data for each month in the year.
with cust as
(
    select distinct CustomerID 
    from @CustomerPayments
)
select * from @CustomerPayments cp
union
select c.CustomerID, 
(select dp.MonthNumber
 from @DummyPayments dp 
 where dp.MonthNumber not in (select cp.MonthNumber from @CustomerPayments cp where cp.CustomerID = c.CustomerID)),
 0
from cust c

运行时出现错误

  

子查询返回了多个值。当子查询遵循=,!=,<,<=,>,> =或将子查询用作表达式时,不允许这样做。

我认为用联合体执行此操作是可行的,并且我理解错误告诉我在每个子查询中得到的结果太多,但是缺少使用游标的方法,我不知道如何执行此操作。也许我已经使它复杂化了,但是如果有人可以帮助我,我将不胜感激。

1 个答案:

答案 0 :(得分:3)

使用vec生成行,然后使用cross join引入现有结果:

left join