我每个月和每个客户都有销售数据报告。当我计算值时,由于sparsa数据格式,没有报告零值.
假设客户1-4。假设只有客户1-2有录音。直表在行和列上有月份的customerIDs,这样
|CustomerID|MonthID|Value|
-------------------------|
| 1 |201101 | 10 |
| 2 |201101 | 100 |然后,它们以交叉表格式报告,以便
|CustomerID|201101|201102|2011103|...|201501|
---------------------------------------------
| 1 | 10 | 0 | 0 |...| 0 |
| 2 | 100 | 0 | 0 |...| 0 |
| 3 | 0 | 0 | 0 |...| 0 |
| 4 | 0 | 0 | 0 |...| 0 |当我数这个,我没有得到任何客户3-4,因为他们没有录音。我想得到丢失的零行。如何填充或选择原始数据并将不存在的零值填充到所选内容中?或者更短的时间:
是处理稀疏数据格式的最优雅的方法,在最终报告中仍然有零客户?
发布于 2017-04-29 11:05:16
在转到交叉表格式之前,您可以使用cross join表Customers和Months,然后将left join表Sales转到交叉表格式。
select
c.CustomerId
, m.MonthId
, Value = isnull(s.Value,0)
from customers c
cross join months m
left join sales s
on s.CustomerId = c.CustomerId
and s.MonthId = m.MonthIdrextester演示:http://rextester.com/XKU62242
返回:
+------------+---------+-------+
| CustomerId | MonthId | Value |
+------------+---------+-------+
| 1 | 201101 | 10 |
| 2 | 201101 | 100 |
| 3 | 201101 | 0 |
| 4 | 201101 | 0 |
| 1 | 201102 | 0 |
| 2 | 201102 | 0 |
| 3 | 201102 | 0 |
| 4 | 201102 | 0 |
| 1 | 201103 | 0 |
| 2 | 201103 | 0 |
| 3 | 201103 | 0 |
| 4 | 201103 | 0 |
+------------+---------+-------+向上面添加一个动态pivot()可以如下所示:
declare @cols nvarchar(max);
declare @sql nvarchar(max);
select @cols = stuff((
select ',' + quotename(MonthId)
from months
order by MonthId
for xml path (''), type).value('.','nvarchar(max)')
,1,1,'');
select @sql = '
select CustomerId, ' + @cols + '
from (
select
c.CustomerId
, m.MonthId
, Value = isnull(s.Value,0)
from customers c
cross join months m
left join sales s
on s.CustomerId = c.CustomerId
and s.MonthId = m.MonthId
) as t
pivot (sum([Value]) for [MonthId] in (' + @cols + ') ) p';
select @sql as CodeGenerated;
exec sp_executesql @sql;返回:
+-----------------------------------------------------------------------+
| CodeGenerated |
+-----------------------------------------------------------------------+
| select CustomerId, [201101],[201102],[201103] |
| from ( |
| select |
| c.CustomerId |
| , m.MonthId |
| , Value = isnull(s.Value,0) |
| from customers c |
| cross join months m |
| left join sales s |
| on s.CustomerId = c.CustomerId |
| and s.MonthId = m.MonthId |
| ) as t |
| pivot (sum([Value]) for [MonthId] in ([201101],[201102],[201103]) ) p |
+-----------------------------------------------------------------------+exec返回:
+------------+--------+--------+--------+
| CustomerId | 201101 | 201102 | 201103 |
+------------+--------+--------+--------+
| 1 | 10 | 0 | 0 |
| 2 | 100 | 0 | 0 |
| 3 | 0 | 0 | 0 |
| 4 | 0 | 0 | 0 |
+------------+--------+--------+--------+https://stackoverflow.com/questions/43694372
复制相似问题