我有一个存储不同类型的程序"资产"对于可以标记为"已删除"的建筑物。我可以创建一个查询来计算按类型划分的资产数量,另一个可以计算标识为仍然存在的项目数。但我想要做的是将两者合并为一张表。
查询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 :(得分: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;
这会将值放在同一行的不同列中 - 这对我来说比在单独的行上更有意义。
答案 1 :(得分: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
答案 2 :(得分: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
答案 3 :(得分: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 buildingID=@buildingID
GROUP BY theAssetOutletType) AS nested
RIGHT JOIN tblLEGAssetOutletTypes ON nested.theAssetOutletType = tblLEGAssetOutletTypes.assetOutletType;