SQL-Server:返回COUNT(*)大于或等于3的字段

时间:2015-11-27 03:40:19

标签: sql sql-server

我想仅针对那些> = 3

COUNT获得结果
SELECT CustomerNBene.Company, ContractLog.userID
       , CONVERT (varchar(10) ,ContractLog.date, 103) as [date]
       , CONVERT (varchar(10), ContractLog.LValueDate, 103) as LValueDate
       , Payable.ContractNo
       , Payable.bank
       , Payable.currency
       , Payable.Amount
       , (
          SELECT Count(*)
          FROM DimDate
          WHERE DimDate.[Date] BETWEEN CONVERT (varchar(10) ,ContractLog.[date], 112) 
          AND CONVERT (varchar(10), ContractLog.LValueDate, 112) AND DimDate.isweekEND = 0
        ) as Payable
FROM CustomerNBene, ContractLog, Payable
WHERE ContractLog.contractNo = Payable.ContractNo
AND ContractLog.LConStatus = 'VAL'
AND CustomerNBene.ConNo = ContractLog.contractNo
AND CustomerNBene.CustID != '01'
AND (Payable.Confirmed is NULL or Payable.Confirmed = 'N')
ORDER BY Payable desc, bank

当我添加AND Payable >= 3时,我会收到“无效的列名称”

我该如何去做?

2 个答案:

答案 0 :(得分:0)

解决方法是使用temptable,在temptable中插入上面查询的结果集,然后在临时表中应用过滤器。

试试这个..

 SELECT CustomerNBene.Company, ContractLog.userID
       , CONVERT (varchar(10) ,ContractLog.date, 103) as [date]
       , CONVERT (varchar(10), ContractLog.LValueDate, 103) as LValueDate
       , Payable.ContractNo
       , Payable.bank
       , Payable.currency
       , Payable.Amount
       , (
          SELECT Count(*)
          FROM DimDate
          WHERE DimDate.[Date] BETWEEN CONVERT (varchar(10) ,ContractLog.[date], 112) 
          AND CONVERT (varchar(10), ContractLog.LValueDate, 112) AND DimDate.isweekEND = 0
        ) as Payable
INTO #TempTable -->> Insert into temp table
FROM CustomerNBene, ContractLog, Payable
WHERE ContractLog.contractNo = Payable.ContractNo
AND ContractLog.LConStatus = 'VAL'
AND CustomerNBene.ConNo = ContractLog.contractNo
AND CustomerNBene.CustID != '01'
AND (Payable.Confirmed is NULL or Payable.Confirmed = 'N')
ORDER BY Payable desc, bank

-->> now apply the filtering in temp table
SELECT Company, userID, date, LValueDate, ContractNo, bank, currency, Amount, Payable
FROM #TempTable
GROUP BY Company, userID, date, LValueDate, ContractNo, bank, currency, Amount, Payable
HAVING COUNT([Payable]) >= 3

答案 1 :(得分:0)

您需要知道查询中的语句执行的逻辑顺序,您可以从下面的链接下载海报并按照数字查看下一个执行的操作符

http://tsql.solidq.com/books/insidetsql2008/Logical%20Query%20Processing%20Poster.pdf

简单来说

以下查询无法正常工作

select name,sum(id) as summ
from test
where summ=10

你可以将它包装在cte.CTE中是一个disposbale视图,它在DB中没有实现,但对于单个执行的范围有效

;with cte
as
(
select name,sum(id) as summ
from test
where summ=10
)
select * from cte where summ=10