给出以下源表。
CREATE TABLE prices
(
Style CHAR(10),
Size CHAR(10),
BeginDate DATE,
EndDate DATE,
price DECIMAL(18, 2)
)
INSERT INTO prices
(Style,
Size,
BeginDate,
EndDate,
price)
VALUES ('B100',NULL,'1-10-2010','1-30-2010',-5),
('B101',NULL,'1-10-2010','1-15-2010',-10),
('B102',NULL,'1-10-2010','1-15-2010',-20),
('B100','32x32','1-10-2010','1-15-2010',-1),
('B100','32x34','1-11-2010','1-20-2010',-2),
('B100','32x36','1-01-2010','1-15-2010',-3),
('B100','32x38','1-10-2010','2-15-2010',-4)
CREATE TABLE Products
(
ProductKey INT,
Style CHAR(10),
Size CHAR(10)
)
INSERT INTO Products
(ProductKey,
Style,
Size)
VALUES (1,'B100','32x32'),
(2,'B100','32x34'),
(3,'B100','32x36'),
(4,'B100','32x38'),
(5,'B100','32x40'),
(6,'B101','32x32'),
(7,'B101','32x34'),
(8,'B101','32x36'),
(9,'B101','32x38'),
(10,'B101','32x40'),
(11,'B102','32x32'),
(12,'B103','32x34'),
(13,'B103','32x36'),
(14,'B103','32x38'),
(15,'B103','32x40')
我需要生成以下输出
ProductKey BeginDate EndDate Price
1 1-10-2010 1-15-2010 -1
1 1-16-2010 1-30-2010 -5
2 1-10-2010 1-10-2010 -5
2 1-11-2010 1-20-2010 -2
2 1-21-2010 1-30-2010 -5
etc....
所以价格表是折扣的SCD。折扣可以在样式级别或单个大小级别应用。
尺寸级别折扣会覆盖特定时间段的样式级别折扣。无论如何,时间段可以重叠。
The question is similar to the one I asked a year ago.我试图在不诉诸游标或循环的情况下如何做到这一点时遇到了很多问题。
感谢您的帮助。
答案 0 :(得分:0)
WITH cte AS (
SELECT p.*,s1.BeginDate, s1.EndDate, s1.price
FROM Products p
INNER JOIN prices s1
ON p.Style = s1.Style
AND p.Size = s1. Size
)
SELECT *
FROM cte
UNION ALL
SELECT
c.PRODUCTKEY, c.STYLE, c.SIZE
, DATEADD(day,1,c.EndDate)
, s.EndDate
, s.Price
FROM cte c
INNER JOIN prices s
ON c.Style = s.Style
AND s.Size IS NULL
AND c.EndDate > s.BeginDate AND c.EndDate < s.EndDate
UNION ALL
SELECT
c.PRODUCTKEY, c.STYLE, c.SIZE
, s.BeginDate
, DATEADD(day,-1,c.BeginDate)
, s.Price
FROM cte c
INNER JOIN prices s
ON c.Style = s.Style
AND s.Size IS NULL
AND c.BeginDate > s.BeginDate AND c.BeginDate < s.EndDate
ORDER BY ProductKey,BeginDate