我有一个表(SQL Server 2017),其中的数据按年和周的级别存储。
+---------+-------------+---------+----------+-----+
| year_id | week_number | good_id | store_id | qty |
+---------+-------------+---------+----------+-----+
| 2019 | 42 | 113466 | 41 | 7 |
+---------+-------------+---------+----------+-----+
我需要得到一个类似的表,但是在日级别,每天的数量(数量)将平均分为7个部分。
+---------+-------------+---------+----------+-----+------------+
| year_id | week_number | good_id | store_id | qty | date_id |
+---------+-------------+---------+----------+-----+------------+
| 2019 | 42 | 113466 | 41 | 1 | 2019-10-14 |
+---------+-------------+---------+----------+-----+------------+
| 2019 | 42 | 113466 | 41 | 1 | 2019-10-15 |
+---------+-------------+---------+----------+-----+------------+
| 2019 | 42 | 113466 | 41 | 1 | 2019-10-16 |
+---------+-------------+---------+----------+-----+------------+
| 2019 | 42 | 113466 | 41 | 1 | 2019-10-17 |
+---------+-------------+---------+----------+-----+------------+
| 2019 | 42 | 113466 | 41 | 1 | 2019-10-18 |
+---------+-------------+---------+----------+-----+------------+
| 2019 | 42 | 113466 | 41 | 1 | 2019-10-19 |
+---------+-------------+---------+----------+-----+------------+
| 2019 | 42 | 113466 | 41 | 1 | 2019-10-20 |
+---------+-------------+---------+----------+-----+------------+
我找到了进入get a date from the year and week number的方法,但是如何一次获得7行呢?
答案 0 :(得分:2)
您可以创建一个日历表,如图here所示 并按如下所示连接原始表以获得所需的输出。
Select
CalendarDate
, year_id
, week_number
, good_id
, store_id
, 1 as qty
from dbo.RunningNumbers
inner join ToBeGenerated on CalendarYear = year_id and week_number = CalendarWeek
这是现场db<>fiddle演示。
答案 1 :(得分:1)
你去了。您需要将具有所有日期的表联接起来,然后将数量除以所需的值:
use tempdb
CREATE TABLE tbl1
(
year_id INT, week_number INT, good_id INT, store_id INT, qty INT
)
INSERT INTO tbl1
VALUES (2019, 42, 113466, 41, 7)
GO
WITH sample AS(
SELECT CAST('2019-10-01' AS DATE) as DT
UNION ALL
SELECT DATEADD(dd,1,dt)
FROM sample
WHERE DATEADD(dd,1,dt) < CAST('2019-12-31' AS DATE))
SELECT dt, YEAR(dt) AS [Year], DATEPART(WEEK,dt) AS Week
INTO wks
FROM sample
SELECT t.year_id, t.week_number, t.good_id, t.store_id, qty/7 AS [Qty], dt AS [Date]
FROM tbl1 t
INNER JOIN wks S on s.Week = t.week_number