4

这是我的问题的一个简单示例。我有一个创建报告的存储过程。

DECLARE @Report TABLE
(Product VARCHAR(10),
Purchases MONEY default (0) 
)
DECLARE @Range TABLE
(minP MONEY,
maxP MONEY,
Descrip VARCHAR(50)
)

INSERT @Range
VALUES(0,1,'0-1'),
(2,5,'2-5'),
(6,10,'6-10')

INSERT @Report(Product, Purchases)
VALUES('A',1),
('A',5),
('B',10)


SELECT r.Product, r.Purchases, x.Descrip  
FROM @Report r CROSS JOIN @Range x 
WHERE r.purchases BETWEEN x.minp AND x.maxp

结果如下所示:

Product Purchases   Descrip
A   1.00    0-1
A   5.00    2-5
B   10.00   6-10

我怎样才能让结果看起来像这样:

Product Purchases   Descrip
A   1.00    0-1
A   5.00    2-5
A   0   6-10
B   0   0-1
B   0   2-5
B   10.00   6-10
4

2 回答 2

3

这应该这样做:

SELECT B.Product, ISNULL(C.Purchases,0) Purchases, A.Descrip
FROM @Range A
CROSS JOIN (SELECT DISTINCT Product
            FROM @Report) B
LEFT JOIN @Report C
    ON B.Product = C.Product 
    AND C.Purchases BETWEEN A.minP AND A.maxP
ORDER BY B.Product, Purchases

这是一个演示供您尝试。

于 2013-01-04T19:20:45.690 回答
3

你可以尝试这样的事情:

  • 交叉加入具有范围的不同产品列表以获得每个组合。
  • 左加入这个交叉加入的列表与原始报告原始数据填写购买数据。
  • 连接关系将与您的原始where子句具有相同的逻辑(加上链接product

示例查询

SELECT
  r2.Product,
  coalesce(r.Purchases, 0) as Purchases,
  x.Descrip  
FROM 
  (select distinct Product from @Report) r2 CROSS JOIN @Range x
    left join @Report r on r.purchases BETWEEN x.minp AND x.maxp
                        and r.product = r2.product

样本输出(演示):

| PRODUCT | PURCHASES | DESCRIP |
---------------------------------
|       A |         1 |     0-1 |
|       A |         5 |     2-5 |
|       A |         0 |    6-10 |
|       B |         0 |     0-1 |
|       B |         0 |     2-5 |
|       B |        10 |    6-10 |

我会假设您的实际数据比这复杂得多。例如,如果在一个范围内有多次购买,我不确定您期望什么样的结果。但这至少应该让你开始。

于 2013-01-04T19:21:14.113 回答