使用CTE中的现有行创建新行

时间:2014-05-05 22:57:48

标签: sql sql-server common-table-expression

我想在SQL Server视图中从现有行创建新行

原始视图如下

              salecount   

  HP           56
  Dell         32
  Acer         21
  Asus         55
 ..........many rows

输出视图如下

                    salecount
HP Laptop           44.8 (56*0.8)

HP Desktop          11.2 (56*0.2)
  Dell              32
  Acer              21
  Asus              55

 ..........many rows

我不知道如何在CTE内部使用插入

,CTE_SalesSeparated
AS(
SELECT [Date]
      ,[Country]
      ,[Year]
      ,[Brand]
     -- ,Insert into 'HP Laptop'  = [SaleCount]*0.8
     --              'HP Desktop' = [SaleCount]*0.2
FROM CTE_Sales
)

谢谢大家。

1 个答案:

答案 0 :(得分:1)

你想做这样的事吗?

WITH CTE_SalesSeparated AS (
      SELECT s.[Date], s.[Country], s.[Year],
             coalesce(ld.[Brand] + ' ' + which, s.Brand) as Brand,
             s.SalesCount * coalesce(ld.factor, 1) as SalesCOunt
      FROM CTE_Sales s LEFT JOIN
           (SELECT 'HP' as Brand, 'LapTop' as which, 0.8 as factor UNION ALL
            SELECT 'HP' as Brand, 'DeskTop' as which, 0.2 as factor
           ) ld
           ON s.Brand = ld.Brand
     )