我有以下结构。我想要实现的是,如果由于某种原因其中一个类别不存在,那么与其没有该类别的行,不如应该有一个 x/y/z 为零的行。
以下内容似乎有点令人费解-实现此目的的正确方法是什么?
TRUNCATE TABLE dbo.xxx;
INSERT INTO dbo.xxx
values
('cat_1',0.0,0.0,0.0),
('cat_2',0.0,0.0,0.0),
('cat_3',0.0,0.0,0.0),
('cat_4',0.0,0.0,0.0);
--:: category 1
INSERT INTO dbo.xxx
SELECT Category = 'cat_1',
x = SUM(x),
y = SUM(y),
z = SUM(z)
FROM dbo.yyy x
WHERE DateKey >= period1;
--:: category 2
INSERT INTO dbo.xxx
SELECT Category = 'cat_2',
x = SUM(x),
y = SUM(y),
z = SUM(z)
FROM dbo.yyy x
WHERE DateKey >= period2;
--:: category 3
INSERT INTO dbo.xxx
SELECT Category = 'cat_3',
x = SUM(x),
y = SUM(y),
z = SUM(z)
FROM dbo.yyy x
WHERE DateKey >= period3;
--:: category 4
INSERT INTO dbo.xxx
SELECT Category = 'cat_4',
x = SUM(x),
y = SUM(y),
z = SUM(z)
FROM dbo.yyy x
WHERE DateKey >= period4;
SELECT Category,
x = SUM(x),
y = SUM(y),
z = SUM(z)
INTO #temp
FROM dbo.xxx
GROUP BY Category;
TRUNCATE TABLE dbo.xxx;
INSERT INTO dbo.xxx
SELECT * FROM #temp;