使用CTE需要SQL Query

时间:2012-07-04 06:03:14

标签: sql

任何人都可以帮我写一个SQL查询,定义如下: 我有两个表Itemtype和Items

Itemtype
-------------------
ItemTypeID ItemParent TypeName
-------------------------------
1           0          XXX
2           1          YYY
3           1          ZZZ
4           0          SSS
5           4          GGG

Items
--------------------
ItemID ItemTypeID ItemCost
----------------------------------
1        1         5000
2        2        1000
3        4        250
4        3        2000
5        5        400

Output
---------------------------
ItemtypeName ItemCost
------------------------------
XXX            8000 (1000+5000+2000)
SSS            650 (250+400)

这两个表:我使用itemtypeid加入了两个表。 现在我需要显示ItemParentId = 0的Items 和 使用itemtypeId和ItemparentTypeId计算项目的Itemcost,其值与ItemTypeID的值相同。

我使用CTE编写了一个查询,但它没有显示ItemTypeName。

WITH it_cte AS ( select itemtypeid from ItemType WHERE
ItemType.ItemParentType IS NULL UNION ALL select i.ItemTypeid from
ItemType i  INNER JOIN it_cte icte ON icte.itemtypeid = i.itemtypeid )
select ItemParentType,SUM(Items.ItemCost) as itemcost from ItemType 
left join Items on ItemType.ItemTypeID = Items.ItemTypeID  or
ItemType.ItemParentType= Items.ItemTypeID  group by
ItemType.ItemParentType

有人可以帮忙吗?

由于 贾木纳

1 个答案:

答案 0 :(得分:3)

以下声明

  • 使用CTE检索每个ItemTypeID及其根ItemTypeID
  • 的列表
  • ItemType加入以获取TypeName
  • Items加入以获取ItemCost
  • TypeName上的小组获取ItemCost
  • 的总和

SQL声明

;WITH q AS (
  SELECT  ItemTypeID , Root = ItemTypeID
  FROM    ItemType
  WHERE   ItemParent = 0
  UNION ALL
  SELECT  t.ItemTypeID, q.Root
  FROM    q
          INNER JOIN ItemType t ON t.ItemParent = q.ItemTypeID
) 
SELECT  it.TypeName, SUM(i.ItemCost)
FROM    q
        INNER JOIN ItemType it ON it.ItemTypeID = q.Root
        INNER JOIN Items i ON i.ItemTypeID = q.ItemTypeID
GROUP BY
        it.TypeName        

测试脚本

;WITH ItemType (ItemTypeID, ItemParent, TypeName) AS (
  SELECT 1, 0, 'XXX' UNION ALL
  SELECT 2, 1, 'yyy' UNION ALL
  SELECT 3, 1, 'ZZZ' UNION ALL
  SELECT 4, 0, 'SSS' UNION ALL
  SELECT 5, 4, 'GGG'
)
, Items (ItemID, ItemTypeID, ItemCost) AS (
  SELECT 1, 1, 5000 UNION ALL
  SELECT 2, 2, 1000 UNION ALL
  SELECT 3, 4, 250 UNION ALL
  SELECT 4, 3, 2000 UNION ALL
  SELECT 5, 5, 400
)
, q AS (
  SELECT  ItemTypeID , Root = ItemTypeID
  FROM    ItemType
  WHERE   ItemParent = 0
  UNION ALL
  SELECT  t.ItemTypeID, q.Root
  FROM    q
          INNER JOIN ItemType t ON t.ItemParent = q.ItemTypeID
) 
SELECT  it.TypeName, SUM(i.ItemCost)
FROM    q
        INNER JOIN ItemType it ON it.ItemTypeID = q.Root
        INNER JOIN Items i ON i.ItemTypeID = q.ItemTypeID
GROUP BY
        it.TypeName