如何更改并插入新表?

时间:2015-03-18 15:33:01

标签: sql sql-server insert

这是我的疑问:

SELECT TOP 50 
    ch.CharName16, it.OptLevel, obj.ReqLevel1, item.ItemClass  
FROM 
    _Items as it            
LEFT JOIN 
    [dbo].[_Inventory] as inv ON it.ID64 = inv.ItemID   
LEFT JOIN 
    [dbo].[_Char] as ch ON inv.CharID = ch.CharID           
LEFT JOIN 
    [dbo].[_RefObjCommon] as obj ON it.RefItemID = obj.ID           
LEFT JOIN 
    [dbo].[_RefObjItem] as item ON obj.Link = item.ID           
LEFT JOIN 
    [dbo].[_BindingOptionWithItem] as adv ON it.ID64 = adv.nItemDBID            
WHERE 
    ch.CharName16 IS NOT NULL 
    AND CodeName128 NOT LIKE '%stone%' 
    AND CharName16 NOT LIKE '%]%'           
ORDER BY 
    it.OptLevel DESC, obj.ReqLevel1 DESC, item.ItemClass DESC,
    adv.nOptValue DESC

查询结果:

query results

我想将这些添加到新表中,但是像这样:

desired results

我该怎么做?

2 个答案:

答案 0 :(得分:1)

您可以使用外部查询来包装查询,该外部查询执行所需的聚合,如您所需的结果所示,将数据滚动起来(如果删除TOP 50,则需要删除ORDER BY)。然后使用聚合数据执行INSERT。像这样的东西应该可以正常工作。

INSERT INTO MyTable(
        CharName16
        , OptLevel
        , ReqLevel1
        , ItemClass
        , TotalPoint
        )
SELECT CharName16
        , SUM(OptLevel) AS OptLevel
        , SUM(ReqLevel1) AS ReqLevel1
        , SUM(ItemClass) AS ItemClass
        , SUM(OptLevel) + SUM(ReqLevel1) + SUM(ItemClass) AS TotalPoint
  FROM (
        SELECT TOP 50 ch.CharName16, it.OptLevel, obj.ReqLevel1, item.ItemClass  
          FROM _Items as it            
          LEFT JOIN [dbo].[_Inventory] as inv ON it.ID64 = inv.ItemID   
          LEFT JOIN [dbo].[_Char] as ch ON inv.CharID = ch.CharID           
          LEFT JOIN [dbo].[_RefObjCommon] as obj ON it.RefItemID = obj.ID           
          LEFT JOIN [dbo].[_RefObjItem] as item ON obj.Link = item.ID           
          LEFT JOIN [dbo].[_BindingOptionWithItem] as adv ON it.ID64 = adv.nItemDBID            
         WHERE ch.CharName16 IS NOT NULL 
           AND CodeName128 NOT LIKE '%stone%' 
           AND CharName16 NOT LIKE '%]%'           
       ) tbl
 GROUP BY CharName16

答案 1 :(得分:0)

SELECT TOP 50  
    ch.CharName16, 
    Sum(it.OptLevel)as OptLevel, 
    Sum(obj.ReqLevel1)as ReqLevel1, 
    Sum(item.ItemClass) as ItemClass,
    Sum(SUM(it.OptLevel)+ SUM(obj.ReqLevel1)+ SUM(item.ItemClass)) as TotalPoint

 INTO NEWTABLE

FROM 
    _Items as it            
LEFT JOIN 
    [dbo].[_Inventory] as inv ON it.ID64 = inv.ItemID   
LEFT JOIN 
    [dbo].[_Char] as ch ON inv.CharID = ch.CharID           
LEFT JOIN 
    [dbo].[_RefObjCommon] as obj ON it.RefItemID = obj.ID           
LEFT JOIN 
    [dbo].[_RefObjItem] as item ON obj.Link = item.ID           
LEFT JOIN 
    [dbo].[_BindingOptionWithItem] as adv ON it.ID64 = adv.nItemDBID            
WHERE 
    ch.CharName16 IS NOT NULL 
    AND CodeName128 NOT LIKE '%stone%' 
    AND CharName16 NOT LIKE '%]%'           
ORDER BY 
    it.OptLevel DESC, obj.ReqLevel1 DESC, item.ItemClass DESC,
    adv.nOptValue DESC