我很难尝试创建一个包含SQL Server Management Studio 17中表的重复值的视图。
我的表格如下:
DATE = datetime
Product = varchar(10)
Price = decimal(18,2)
Date | Product | Price
07-12-17 | 1 | 32
06-12-17 | 24 | 35
每天有1-24种产品。
我想创建以下视图表:
Date | Product | Price
07-12-17 | 1.1 | 32
07-12-17 | 1.2 | 32
07-12-17 | 1.3 | 32
07-12-17 | 1.4 | 32
06-12-17 | 24.1 | 35
06-12-17 | 24.2 | 35
06-12-17 | 24.3 | 35
06-12-17 | 24.4 | 35
每天所有24种产品都是如此。
答案 0 :(得分:2)
尝试将CROSS JOIN
与VALUES
SELECT
t.[Date],
CONCAT(t.Product,'.',l.num) ProductLabel,
t.Price
FROM [Your table] t
CROSS JOIN (VALUES(1),(2),(3),(4)) l(num)
ORDER BY t.[Date],t.Product,l.num
变体UNION ALL
SELECT
t.[Date],
t.Product+'.'+l.Label ProductLabel,
t.Price
FROM [Your table] t
CROSS JOIN
(
SELECT '1' Label UNION ALL SELECT '2' UNION ALL SELECT '3' UNION ALL SELECT '4'
) l
ORDER BY t.[Date],t.Product,l.Label
如果您有另一个包含数字1-4的行的表,那么您可以对该表使用CROS JOIN
SELECT
t.[Date],
CONCAT(t.Product,'.',l.[ID from another table]) ProductLabel,
t.Price
FROM [Your table] t
CROSS JOIN [Your table with numbers] l
ORDER BY t.[Date],t.Product,l.[ID from another table]
如果您只需要4个重复项,那么您还可以使用UNION ALL
SELECT [Date],Product+'.1' ProductLabel,Price FROM [Your table]
UNION ALL SELECT [Date],Product+'.2',Price FROM [Your table]
UNION ALL SELECT [Date],Product+'.3',Price FROM [Your table]
UNION ALL SELECT [Date],Product+'.4',Price FROM [Your table]
ORDER BY [Date],ProductLabel