SQL Query.unable查找资产计数

时间:2013-07-01 11:32:33

标签: sql join

我有两个表Assets_In和Assets_Out。我想知道我的库存资产。

Assets_IN

ASSET_TYPE  ASSET_IN_COUNT
Laptops             3
Desktops            2
Desktops            2
Laptops             2
Laptops             2
Keyboards           5
Keyboards           5
Monitors            4
AC Adapters         3
Mouse               10
Monitors            2
Monitors            2
Backpacks           10
Desktops            2
Backpacks           3

Asset_Out

ASSET_TYPE  ISSUED_TO
Desktops    Ram
Monitors    Shyam
Keyboards   Ranjan

我写了2个查询,但我无法将这两个问题结合起来以实现我的结果。

SELECT ASSET_TYPE Asset, SUM(ASSET_IN_COUNT) Count 
FROM ASSETS_IN GROUP BY ASSET_TYPE

这给了我们收到的资产数量

SELECT ASSET_TYPE Asset,COUNT(ASSET_TYPE) 
FROM ASSETS_OUT  GROUP BY ASSET_TYPE

显示我们已发放的资产数量。

结果应该显示我们有多少资产。即手头的资产减去已发行的资产。你能帮我解决这个问题。

2 个答案:

答案 0 :(得分:0)

Select a.Asset, a.Asset_in, b.Asset_issued, a.Asset_in - b.Asset_issued 
from
    (SELECT ASSET_TYPE Asset, SUM(ASSET_IN_COUNT) Asset_in Count 
     FROM ASSETS_IN 
     GROUP BY ASSET_TYPE) a

join

    (SELECT ASSET_TYPE Asset,COUNT(ASSET_TYPE) Asset_issued 
     FROM ASSETS_OUT 
     GROUP BY ASSET_TYPE) b

on a.Asset = b.Asset

答案 1 :(得分:0)

试试这个

SELECT ASSET_TYPE AS Asset
, SUM(ASSET_IN_COUNT) - (SELECT COUNT(ASSET_TYPE) FROM ASSETS_OUT 
WHERE ASSET_TYPE=AI.ASSET_TYPE) AS [Count] 
FROM ASSETS_IN AI GROUP BY ASSET_TYPE