2017-10-21 142 views
0

我有一个程序,可以标记为“已删除”,为建筑物存储不同类型的“资产”。我可以创建一个查询来计算按类型划分的资产数量,另一个用于统计被识别为仍然存在的项目数量。但是我想要做的是将两者合并为一张表格。SQL Server:结合查询结果

查询1

SELECT 
    theAssetOutletType, COUNT(id) AS TotalNoOfAssets 
FROM 
    dbo.tblLEGAssets 
WHERE 
    buildingID = 1 
GROUP BY 
    theAssetOutletType 

查询2

SELECT 
    theAssetOutletType, COUNT(id) AS ItemsStillPresent 
FROM    
    dbo.tblLEGAssets 
WHERE 
    buildingID = 1 AND removed <> 0 
GROUP BY 
    theAssetOutletType 

预先感谢您的任何帮助

回答

0

尝试联盟:

SELECT theAssetOutletType, count(id) as TotalNoOfAssets FROM dbo.tblLEGAssets where buildingID=1 group by theAssetOutletType 

UNION 

SELECT theAssetOutletType, count(id) as ItemsStillPresent FROM dbo.tblLEGAssets where buildingID=1 and removed<> 0 group by theAssetOutletType 
+0

如果使用联盟,你需要添加一个标志为每种类型的行,FE 1为AllRows,0作为NotRemoved行 –

+0

感谢信息 - 但是,它似乎只生成TotalNoOfAssets - 仍然存在不会出现:( –

+0

它通常使用第一个查询中的字段名称,而不管后续查询对字段名称有什么作用。 – Wranorn

1

我建议有条件聚集:

SELECT theAssetOutletType, 
     COUNT(*) as TotalNoOfAssets 
     SUM(CASE WHEN removed <> 0 THEN 1 ELSE 0 END) as ItemsStillPresent 
FROM dbo.tblLEGAssets 
WHERE buildingID = 1 
GROUP BY theAssetOutletType; 

这使值在单独的列在同一行 - 这让我更有意义比单独行。

0

我发现周围的工作,通过使用一个嵌套的选择 - 我可以使用,但如果它仍然可能我很想知道答案:

SELECT theassetoutlettype, 
     noofitems, 
     noremoved, 
     noofitems - noremoved AS noLeft 
FROM (SELECT theassetoutlettype, 
       Count(id) AS NoOfItems, 
       Sum(removed) AS noRemoved 
     FROM dbo.tbllegassets 
     WHERE buildingid = 1 
     GROUP BY theassetoutlettype) nested 
0

我终于找到了解决办法......进行了大量的试验和错误,但现在起作用了。这是我的存储过程解决方案,附加表“tblLEGAssetOutletTypes”包含一个包含6种资产​​类型列表的单个字段。以下代码将始终返回6行,其中包含项目类型,资产总数,已删除资产数量和剩余总数。希望别人谁需要类似的问题解决了使用中的代码:

SELECT tblLEGAssetOutletTypes.assetOutletType, nested.NoOfItems, nested.noRemoved, NoOfItems-noRemoved AS noLeft 
FROM (SELECT  theAssetOutletType, COUNT(id) AS NoOfItems, SUM(removed) AS noRemoved 
     FROM   tblLEGAssets 
     where [email protected] 
    GROUP BY theAssetOutletType) AS nested 
RIGHT JOIN tblLEGAssetOutletTypes ON nested.theAssetOutletType = tblLEGAssetOutletTypes.assetOutletType;