连接四个时在两个表中计数值

时间:2019-03-01 08:36:07

标签: sql-server join count substring

我有一个MS SQL问题,无法自行解决。下面是表格。

AREAS
----------------
RA_NAME varchar
RA_DESC varchar

AD_Results
-------------------
AssetName varchar
Parent_Counter varchar (the RA Name is somewhere within that field)

tblAssets
-----------
AssetID int

tblADComputers
----------------
AssetID int
OU varchar (the RA Name is somewhere within that field)

我想读取带有RA名称和描述的表AREAS,并根据它们的RA计算AD_Results中AssetName的数量,然后也根据RA名称对tblAssets中的AssetID进行计数。

公共的“键”是RA名称,但不是这些表中的键字段;实际上是普通字段的子字符串。

两个单个查询可以正常工作,将它们组合成一个,可以在RA_AD_Objects中提供疯狂的高价值。

我试图得到这样的列表

RA_NAME RA_DESC RA_AD_Objects   RA_LS_Push
RA001   X01-01  549909          279
RA002   X02-02  635             0
RA004   X03-04  259306          409

我的查询如下:

 CREATE View AD_LS_CNT AS
 SELECT
        AREAS.RA_NAME
    ,   AREAS.RA_DESC
    ,   COUNT(CASE
                WHEN CharIndex('/RA', AD_Results.[Parent Container]) > 1
                THEN
                SubString(AD_Results.[Parent Container], CharIndex('/RA', AD_Results.[Parent Container]) + 1, 5)
                When CharIndex('/SH', AD_Results.[Parent Container]) > 1
                THEN
                SubString(AD_Results.[Parent Container], CharIndex('/SH', AD_Results.[Parent Container]) + 1, 5)
                ELSE
                'N.A.'
              End) AS RA_AD_Objects
    ,   COUNT( DISTINCT tblAssets.AssetID) AS RA_LS_Push
FROM AREAS
JOIN AD_Results ON CHARINDEX(AREAS.RA_NAME, AD_Results.[Parent Container]) > 0
LEFT JOIN tblADComputers ON CHARINDEX(AREAS.RA_NAME, tblADComputers.OU) > 0
LEFT JOIN tblAssets ON tblAssets.AssetID = tblADComputers.AssetID
GROUP BY AREAS.RA_NAME, AREAS.RA_DESC
ORDER BY AREAS.RA_NAME
GO

2 个答案:

答案 0 :(得分:0)

您可以尝试

SUM(CASE WHEN CHARINDEX(AREAS.RA_NAME, AD_Results.[Parent Container]) > 0 THEN 1 ELSE 0 END) AS  RA_AD_Objects

答案 1 :(得分:0)

经过一个周末的分析,我得到了答案:

SELECT
        AREAS.RA_NAME
    ,   AREAS.RA_DESC
    ,   COUNT( DISTINCT AD_Results.Name) AS RA_AD_Objects
    ,   COUNT( DISTINCT tblAssets.AssetID) AS RA_LS_Objects
FROM AREAS
JOIN AD_Results ON CHARINDEX(AREAS.RA_NAME, AD_Results.[Parent Container]) > 0
LEFT JOIN tblADComputers ON CHARINDEX(AREAS.RA_NAME, tblADComputers.OU) > 0
LEFT JOIN tblAssets ON tblAssets.AssetID = tblADComputers.AssetID
GROUP BY AREAS.RA_NAME, AREAS.RA_DESC
ORDER BY AREAS.RA_NAME
GO

整个COUNT(CASE ...混合了它,实际上并不需要。