需要有关在SQL / SQL Server

时间:2016-02-09 05:33:13

标签: sql sql-server

我是Sql Server的新手

我需要根据以下要求构建查询。请帮助我实现它。

表格中的数据

Store | Product | Price | FromDate   | ToDate
S1    | P1      | 50    | 1-Feb-2016 | 1-Feb-2016
S1    | P1      | 150   | 2-Feb-2016 | NULL
S1    | P2      | 20    | 1-Feb-2016 | NULL
S1    | P3      | 30    | 1-Feb-2016 | 1-Feb-2016

来自用户的输入:日期考虑2016年2月3日

必需输出:

Store | Product | Price | Date
S1    | P1      | 50    | 1-Feb-2016
S1    | P1      | 150   | 2-Feb-2016
S1    | P1      | 150   | 3-Feb-2016
S1    | P2      | 20    | 1-Feb-2016
S1    | P2      | 20    | 2-Feb-2016
S1    | P2      | 20    | 3-Feb-2016
S1    | P3      | 30    | 1-Feb-2016

此致

2 个答案:

答案 0 :(得分:0)

您的问题需要创建日期序列,而SQL Server没有"准备好使用"解决方案,但你可以在其他线程中找到solutin。 这是您的解决方案,只有5天的范围:

DECLARE @sequence TABLE (number int)
INSERT INTO @sequence(number) VALUES (0), (1), (2), (3), (4), (5)

DECLARE @DateToConsider date = '20160203'
SELECT SP.Store, SP.Product, SP.Price, DATEADD(d, s.number, SP.FromDate) [Date]
(SP.ToDate, @DateToCOnsider))
FROM StoreProduct SP
    INNER JOIN @sequence S ON number <= DATEDIFF(d, SP.FromDate, ISNULL(SP.ToDate, @DateToCOnsider))
ORDER BY Store, Product, [Date]

答案 1 :(得分:0)

此脚本显示了如何实现查询

而不是@data你需要使用你的表。我只是把它用来运行我的解决方案

DECLARE @data TABLE (
Store varchar(10),
Product varchar(10),
Price float,
FromDate date,
ToDate date
)

INSERT INTO @data (Store, Product, Price, FromDate, ToDate)
VALUES
('S1', 'P1', 50, '2016-01-01', '2016-01-01'),
('S1', 'P1', 150, '2016-01-02', NULL),
('S1', 'P2', 20, '2016-01-01', NULL),
('S1', 'P3', 30, '2016-01-01', '2016-01-01')

这是用户输入日期:

DECLARE @userInput date = '2016-01-03'

您将最小日期和用户输入日期之间的所有可用日期填入表变量

DECLARE @allDates TABLE (dt date)

DECLARE @minDate date = (SELECT MIN(FromDate) FROM @data)
WHILE @minDate <= @userInput
BEGIN
    INSERT INTO @allDates (dt) VALUES (@minDate)
    SET @minDate = DATEADD(d, 1, @minDate)
END

这是最后的查询

SELECT t.Store, t.Product, t.Price, dt AS [Date]
from @data t LEFT JOIN @allDates ad ON ad.dt = t.FromDate OR ad.dt = t.ToDate OR (t.ToDate IS NULL AND ad.dt>= t.FromDate)
ORDER BY t.Store, t.Product, dt
相关问题