开发者

sql query join string in group

开发者 https://www.devze.com 2023-03-11 18:58 出处:网络
I have this table structure ProjectExpenses Table: -------------------------------------- ProjectNameExpenseCurrency

I have this table structure

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

I definitely want to group by ProjectName; that much I know but how can I get an output like this

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

I'm looking for a string joining function but I have no clue where to begin looking 开发者_如何学Goor even if something like this is possible with just a sql query.

Any hints as to how to solve this problem would be very much appreciated.


Let's start with a basic query to get us the data we need:

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

We can aggregate a list easily for a single Project like this:

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


Since you're using SQL Server 2000, this will be quite complicated (you need the equivalent of Oracle's listagg() function), see Grouped string aggregation / LISTAGG for SQL Server

0

精彩评论

暂无评论...
验证码 换一张
取 消