Can anybody help me in writing an sql query which is defined below:
I’m having two table Itemtype and 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)
These are the two tables:I joined both table using itemtypeid.
Now i need to display Items with ItemParentId = 0
and
calculate the Itemcost of Items with itemtypeId and ItemparentTypeId having value same as that of ItemTypeID.
I wrote a query using CTE,but its not displaying 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
Can anybody help?
Thanks
Jamuna
Following statement
CTEto retrieve a list of eachItemTypeIDwith its rootItemTypeIDItemTypeto get theTypeNameItemsto get theItemCostTypeNameto get the sum of theItemCostSQL Statement
Test script