SQL Server:按条件分组并赋予功能

时间:2014-11-22 10:14:45

标签: sql sql-server

我在SQL Server中有一个表Test和一个列Name

Name
-----
a
a
a
c
c
b

我写了这个查询:

select *
from (select Name, COUNT(*) as cnt
      from Test
      group by Name 
      having COUNT(*) > 2) as newTbl
where dbo.fn_Test(Name) = 1

dbo.fn_Test SQL Server标量函数的位置:

CREATE FUNCTION [dbo].[fn_Test]
   (@name nvarchar)
RETURNS bigint
AS 
BEGIN
    DECLARE @count int

    SET @count = (SELECT TOP 1 COUNT(*)
                  FROM Tbl
                  WHERE Name  = @name);
    return @count;
END

从第一个查询FROM部分可以看出这个选择得到:

select Name, COUNT(*) as cnt
from Test
group by Name 
having COUNT(*) > 2

输出:

Name cnt
--------
 a    3 

但是在调试查询并输入dbo.fn_Test函数时,它适用于所有名称:

a b c

那么如何创建select才能在函数中只获得名称“a”?

3 个答案:

答案 0 :(得分:1)

首先插入你选择#t

insert into #t 
select Name, COUNT(*) as cnt
      from Test
      group by Name 
      having COUNT(*) > 2)

然后使用cursor调用func

...select dbo.fn_Test(@cursor)

答案 1 :(得分:0)

试试这个

Select Name,Count(Name) from test
Group by Name 
having Count(Name)>2

答案 2 :(得分:0)

我找到解决方案。这是我的解决方案。

select Name, COUNT(*) as cnt
into #tmpTbl
from Tbl
group by Name 
having COUNT(*) >  2


select *
from #tmpTbl
where dbo.fn_Test(Name) = 1

在fn_Test函数中,我得到的是与条件相对应的名字。