TSQL限制记录HAVING子句中count()= 1的位置

时间:2013-12-17 12:06:46

标签: sql-server tsql

好的我有3个表在指定的键上链接

account (accountnumber)
package (packageid, accountnumber)
hostdomain (packageid)

我需要获得只有1个域的所有帐户,这是我目前为止的查询,但它返回所有域。我做错了什么?

select 
    domainname,
    resellerAccountNumber,
    a.accountnumber,
    companyname,
    firstname,
    lastname,
    primaryemail,
    HomePhone
    workphone
FROM account a 
INNER JOIN Package p on p.AccountNumber = a.AccountNumber
INNER JOIN hostdomain hd ON HD.packageId = p.packageID 
GROUP BY 
    domainname, reselleraccountnumber, a.accountnumber, companyname, 
    firstname,lastname,primaryemail, HomePhone,workphone, domainaliasId   
HAVING COUNT(domainname) =1 
    AND domainAliasID = 0 
    AND ResellerAccountNumber in ('','LNC','CFMXHOSTING')

2 个答案:

答案 0 :(得分:1)

在HAVING子句中仅使用聚合:

WHERE
    domainAliasID = 0 
    AND ResellerAccountNumber in ('','LNC','CFMXHOSTING')
GROUP BY
    domainname, reselleraccountnumber, a.accountnumber,
    companyname,firstname,lastname,primaryemail, HomePhone,
    workphone, domainaliasId   
HAVING COUNT(domainname) = 1 

答案 1 :(得分:0)

您正在通过太多字段进行聚合。我想你想要这样的东西:

select min(domainname) as domainname, resellerAccountNumber,
       a.accountnumber, companyname, firstname, lastname, primaryemail,
       HomePhone, workphone
FROM account a INNER JOIN
     Package p
     on p.AccountNumber = a.AccountNumber INNER JOIN
     hostdomain hd ON HD.packageId = p.packageID 
GROUP BY reselleraccountnumber, a.accountnumber, companyname, firstname,
         lastname, primaryemail, HomePhone, workphone, domainaliasId   
HAVING COUNT(domainname) = 1 AND
       domainAliasID = 0 AND
       ResellerAccountNumber in ('','LNC','CFMXHOSTING');

我从domainname中删除了group by(并进行了相关更改)。我不知道如何处理domainaliasid,因为您的问题没有提及有关过滤数据的任何内容,只是汇总了数据。您可能希望将其删除以获得所需内容。