插入零值行

时间:2013-08-20 11:22:09

标签: sql

我有以下结构。我想要实现的是,如果由于某种原因,其中一个类别不存在,那么该类别的行没有行,而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;

1 个答案:

答案 0 :(得分:1)

您可以使用COALESCENVL来定义NULL

的替代方案
--:: category 1
INSERT INTO dbo.xxx
SELECT  Category = 'cat_1',
        x       = COALESCE (SUM(x),0),
        y       = COALESCE (SUM(y),0),
        z       = COALESCE (SUM(z),0)    
FROM    dbo.yyy x
WHERE   DateKey >= period1;