SQL将行添加到我的数据集中作为缺少组的占位符?

时间:2016-09-15 16:40:10

标签: sql sql-server sql-server-2008

寻求一些帮助。让我的数据集有3列:Category,SubCategory和Value。

每个类别不包含每个SubCategory,如果不包含,我想为缺少的Category / SubCategory组合添加一个新的行/占位符,其值为0.

例如:

SELECT distinct(SubCategory) From MyTable returns:
SubCategory-A
SubCategory-B
SubCategory-C
SubCategory-D

让我们说Category1包含SubCategory-A和SubCategory-C。我想为丢失的SubCategories B和D添加占位符/新行,所以最终我的结果看起来像(顺序并不重要):

Category1     SubCategory-A      100
Category1     SubCategory-C      125
Category1     SubCategory-B      0      << new row / placeholder
Category1     SubCategory-D      0      << new row / placeholder

我有多个类别,我想将其应用于此。谁能帮我这个?非常感谢!

4 个答案:

答案 0 :(得分:1)

试试这个:

首先将所有不同的categoryId和subcategoryid插入目标表的临时表

SELECT DISTINCT CategoryIds, SubCategoryIds into #t1 FROM TableC

然后将值插入目标表

INSERT INTO TableC(CategoryIds, SubCategoryIds,Value)
SELECT CategoryIds, SubCategoryIds,0 FROM
(SELECT Distinct CategoryIds From TableA) A 
CROSS JOIN (SELECT Distinct SubCategoryIds From TableA) B 
EXCEPT 
SELECT CategoryIds, SubCategoryIds, 0 FROM #t1

答案 1 :(得分:0)

这是另一个版本。

如果您的桌子很大,那么您使用的任何版本的性能都会受到影响(但只有当它可以以100兆字节为单位进行测量时,我猜)

;WITH cteGaps as (
    select
       cat.Category
      ,subcat.SubCategory
     from (--  All categories
           select distinct Category
            from MyTable
          ) cat
      cross join (--  All subcategories
                  select distinct SubCategory
                   from MyTable
                 ) subcat
    except select
       Category
      ,SubCategory
     from MyTable
    )
INSERT MyTable (Category, SubCategory, Value)
 select Category, SubCategory, 0
  from cteGaps

答案 2 :(得分:0)

这就是我要用的。与其他人类似,但在我看来更容易阅读和理解。也避免使用CTE,我认为这对此没有必要。在大多数情况下,我也更喜欢group by而不是distinct,但同样只是个人偏好。

SELECT a.*, Value = ISNULL(b.Value, 0)
FROM (  -- returns all pairs of category and subcategory
    SELECT *
    FROM (
         SELECT Category
         FROM MyTable
         GROUP BY Category
    ) a
    CROSS JOIN (
        SELECT SubCategory 
        FROM MyTable
        GROUP BY SubCategory
    ) b
) a
LEFT JOIN MyTable b
ON a.Category = b.Category and a.SubCategory = b.SubCategory

您想要的子查询别名 - 我很懒,并使用了ab

答案 3 :(得分:0)

试试这个;

SELECT a.Category,c.SubCategory,ISNULL(b.Value,0) AS Value
FROM MyTable a 
CROSS JOIN Mytable c
LEFT JOIN MyTable b
On c.SubCategory = b.SubCategory
AND a.category = b.Category
GROUP BY   a.Category,c.SubCategory,b.Value