没有函数的交叉应用

Vac*_*ano 3 sql-server-2008 sql-server cross-apply

我想在我的生产数据库之一上运行与此非常相似的查询:

-- Setup the table (Already there in my real scenario)
create table dbo.MyTable(MyValue int, MyGroup varchar(5))
insert into dbo.MyTable values
(56,'I'), (12,'I'), (56, 'II'), (12, 'II'), (56, 'III'), (56, 'IV'), (56, 'V'), (12, 'V')

-- Create a function to cross apply with (I can't make this in my production env)
create function dbo.GetOrderGroup(@groupName varchar(15))
returns @ReturnTable table(GroupValue varchar(8000), GroupName varchar(15))
as                
begin
    DECLARE @groupValue VARCHAR(8000)

    SELECT @groupValue = COALESCE(@groupValue + ', ' 
           + cast(MyValue as VARCHAR(10)), cast(MyValue as VARCHAR(10)))
    FROM MyTable
    where MyGroup = @groupName

    insert into @ReturnTable(GroupValue, GroupName)
    SELECT @groupValue, @groupName 
    return;
end;
go

-- cross apply and get the distinct values
SELECT  grp.GroupValue, count(distinct (grp.GroupValue + grp.GroupName)) as 'Count'
from    MyTable tbl (NOLOCK)
        cross apply dbo.GetOrderGroup(tbl.MyGroup) grp
GROUP BY grp.GroupValue
Run Code Online (Sandbox Code Playgroud)

但是我无权在该数据库上创建用户定义的函数(我是开发人员)。

有没有办法在不使用用户定义的函数(或任何其他“创建”语句)的情况下完成此查询

注意:我尝试对我的函数的内容进行交叉应用,但失败了(我认为交叉应用中不允许使用多语句表达式)。

Aar*_*and 9

SELECT 
  GroupValue = Val, 
  [Count] = COUNT(DISTINCT MyGroup) 
FROM 
(
  SELECT MyGroup, Val = STUFF((SELECT ', ' + RTRIM(MyValue) 
   FROM dbo.MyTable 
   WHERE MyGroup = t.MyGroup 
  FOR XML PATH(''), TYPE).value('.[1]','nvarchar(max)', 1, 2, '')
  FROM dbo.MyTable AS t
) AS x 
GROUP BY Val;
Run Code Online (Sandbox Code Playgroud)