第二个计数函数的SQL查询细化

时间:2013-07-08 12:37:46

标签: sql sql-server

下面是我的查询,但我似乎没有正确的SQL。基本上我试图让第7列从单独的表(C)中显示计数,但是我得到一个错误。有帮助吗?查询工作正常,没有select语句中的第二个计数,但我只是想让第7列从另一个表中获取计数。

select 
    distinct a.auditid,
    a.iav,
    c.VID as 'VMS ID',
    c.severity as 'VMS Severity',
    a.name,
    count (distinct A.dnsname) as 'cat 1s',
    count (distinct c.dnsname) as 'ccri'
from 
    [dbo].[Enterprise 20130703] a
    left join [dbo].[VMS_Retina] c on a.AuditID=c.auditid
    inner join [CCRI 2013] c on a.dnsname=c.DNSName
where
    A.sevcode = 'category i'
    AND A.DNSNAME NOT IN ('autodiscovery,'UNKNOWN')
group by A.auditid, a.iav, a.name, c.VID, c.severity
order by 6 desc

2 个答案:

答案 0 :(得分:1)

您已将c别名用于两个不同的表,将其中一个更改为其他字符并且查询可以正常工作:

select 
    distinct a.auditid,
    a.iav,
    c1.VID as 'VMS ID',
    c1.severity as 'VMS Severity',
    a.name,
    count (distinct A.dnsname) as 'cat 1s',
    count (distinct c2.dnsname) as 'ccri'
from
    [dbo].[Enterprise 20130703] a
    left join [dbo].[VMS_Retina] c1 on a.AuditID = c1.auditid
    inner join [CCRI 2013] c2 on a.dnsname = c2.DNSName
where
    A.sevcode = 'category i'
    AND A.DNSNAME NOT IN ('autodiscovery','UNKNOWN')
group by A.auditid, a.iav, a.name, c1.VID, c1.severity
order by 6 desc

答案 1 :(得分:0)

我不知道您使用的DBMS是什么,但Oracle Distinct必须在顶线,所以可能是这样的:

SELECT 
A.auditid,
A.iav,
A.VMS ID,
A.VMS Severity,
A.name,
A.cat_1s,
A.ccri
FROM (
    SELECT 
        distinct a.auditid,
        count (distinct A.dnsname) as 'cat_1s',
        count (distinct c.dnsname) as 'ccri'
        a.iav,
        c.VID as 'VMS ID',
        c.severity as 'VMS Severity',
        a.name,
    FROM 
        [dbo].[Enterprise 20130703] a
        left join [dbo].[VMS_Retina] c on a.AuditID=c.auditid
        inner join [CCRI 2013] c on a.dnsname=c.DNSName
    where
        A.sevcode = 'category i'
        AND A.DNSNAME NOT IN ('autodiscovery','UNKNOWN')
    group by A.auditid, a.iav, a.name, c.VID, c.severity
    order by 6 desc
) A