sql查询连接组中的字符串

时间:2011-06-08 19:38:17

标签: sql sql-server-2000

我有这个表结构

ProjectExpenses Table:
--------------------------------------
ProjectName    Expense     Currency
--------------------------------------
Foo            10          USD
Foo            20          USD
Foo            100         JPY
Bar            50          EUR
Bar            25          EUR

我绝对想按ProjectName分组;我知道的很多,但我怎么能得到像这样的输出

--------------------------
ProjectName    AllExpenses
--------------------------
Foo            30 USD, 100 JPY
Bar            75 EUR,

我正在寻找一个字符串连接函数,但我不知道从哪里开始查看,或者即使只有sql查询就可以实现这样的事情。

非常感谢任何关于如何解决这个问题的提示。

2 个答案:

答案 0 :(得分:2)

让我们从基本查询开始,为我们提供所需的数据:

select ProjectName, Sum(Expense) as Expenses, Currency
from ProjectExpenses
group by ProjectName, Currency

我们可以轻松地为单个项目汇总列表,如下所示:

declare @ProjectExpenses table
(
ProjectName varchar(500),
Expense int,
Currency varchar(500)
)

insert into @ProjectExpenses (ProjectName, Expense, Currency) values ('Foo', 10, 'USD')
insert into @ProjectExpenses (ProjectName, Expense, Currency) values ('Foo', 20, 'USD')
insert into @ProjectExpenses (ProjectName, Expense, Currency) values ('Foo', 100, 'JYP')
insert into @ProjectExpenses (ProjectName, Expense, Currency) values ('Bar', 50, 'EUR')
insert into @ProjectExpenses (ProjectName, Expense, Currency) values ('Bar', 25, 'EUR')


-- do the deed

declare @ProjectExpenseResults table
(
    ProjectName varchar(255),
    AllExpenses varchar(4000)
);

declare @ProjectName varchar(255);
declare @ExpenseList varchar(4000);

declare c cursor for
    select distinct ProjectName
    from @ProjectExpenses;
open c;
fetch next from c into @ProjectName;

while @@FETCH_STATUS = 0
begin
    set @ExpenseList = null;

    select @ExpenseList = ISNULL(@ExpenseList + ', ', '') + CAST(Expenses as varchar(255)) + ' ' + Currency
    from (
        select Sum(Expense) as Expenses, Currency
        from @ProjectExpenses
        where ProjectName = @ProjectName
        group by Currency
    ) t;

    insert into @ProjectExpenseResults ( ProjectName, AllExpenses )
        values (@ProjectName, @ExpenseList);

    fetch next from c into @ProjectName;
end

close c;
deallocate c;

select * from @ProjectExpenseResults

答案 1 :(得分:1)

由于您使用的是SQL Server 2000,这将非常复杂(您需要相当于Oracle的listagg()函数),请参阅 Grouped string aggregation / LISTAGG for SQL Server