如何使SQL Over Clause在条件SQL Server中工作

时间:2017-12-14 14:37:00

标签: sql sql-server

这是我的问题:

我需要在每个匹配行的数据库中获得第一个结果。我收到了很多行。

原始查询每个custid返回多行:

   select distinct b.custid, name   
        FROM  mth_Charge_Records  a   
        join mth_header b on b.id = a.headerid    

所以,为了获得第一行,我想我会给它们编号,然后把它们编号为1.所以这是查询:

  select distinct b.custid, name,   
         count(custid) OVER (order by custid rows unbounded preceding)   as custcount
     FROM  mth_Charge_Records  a   
     join mth_header b on b.id = a.headerid     

它有效并且行号被计算在内。所以,我试图将custcount添加为条件,但它失败了:

  select distinct b.custid, name,   
         count(custid) OVER (order by custid rows unbounded preceding)   as custcount
     FROM  mth_Charge_Records  a   
     join mth_header b on b.id = a.headerid     
     where custcount = 1   <<--- Added this line

现在我收到的错误是custcount是一个无效的列。

任何帮助或建议都应该受到赞赏。非常感谢:)。

3 个答案:

答案 0 :(得分:2)

看看SELECT (Transact-SQL。您会注意到语句的SELECT部分在<{strong> WHERE后评估为。这意味着您无法通过别名引用SELECT中的列。

您也可能注意到您无法在WHERE子句中使用窗口函数。你可以使用CTE,但我想,或许,你真正想要的是一个HAVING条款。因此:

SELECT mt.custid,
       [name]
FROM mth_Charge_Records mCR
     JOIN mth_header mt on mCR.headerid = mt.id
GROUP BY mt.custid,
         [name]
HAVING COUNT(mt.custid) = 1;

编辑:COUNT在重读后有点误导。你想要一个CTE和ROW_NUMBER

WITH CTE AS(
    SELECT mt.custid,
           [name],
           ROW_NUMBER() OVER (ORDER BY mt.custid) AS RN
    FROM mth_Charge_Records mCR
     JOIN mth_header mt on mCR.headerid = mt.id)
SELECT *
FROM CTE
WHERE RN = 1;

答案 1 :(得分:2)

您在row_number()的尝试将返回任意行。如果这就是您想要的,为什么不使用聚合?

select h.custid, max(crname)  
from mth_Charge_Records cr join
     mth_header h
     on h.id = cr.headerid;

答案 2 :(得分:1)

Try this 
Select a.*
From ( 
select distinct b.custid, name,   
         count(custid) OVER (order by custid rows unbounded preceding)   as custcount
     FROM  mth_Charge_Records  a   
     join mth_header b on b.id = a.headerid 
) a    
     where a.custcount = 1