0

Afternoon All,

I am new to Oracle and SQL but i have a query with the below code i have created. Im currently using Oracle 10g. Im just wondering if anyone can help me make this code dynamic instead of hard coded.

The code i have simply looks at a table that logs the users activity. I then essentially count the number of records that we have for each user / PC and display this in a pivot style table.

Its not a very difficult query as such but i could have about 30 or so PC's that i would need to enter and this hard coded method is definitly not the best way to complete this task.

I have been searching on the internet to look at a dynamic statement i could use based on the host name or user_ID but i have not managed to find anything that simply loops through my data and then generates this piviot style view.

I have been looking at 'Cursors' but im think im way off by a long shot.

Ant help is much appriechiated in advance.

Regards Betty

SELECT USER_ID,
    SUM(CASE WHEN host LIKE 'PC1' THEN 1 ELSE 0 END) AS PC1,
    SUM(CASE WHEN host LIKE 'PC2' THEN 1 ELSE 0 END) AS PC2,
    SUM(CASE WHEN host LIKE 'PC3' THEN 1 ELSE 0 END) AS PC3,
    SUM(CASE WHEN host IS NOT NULL THEN 1 ELSE 0 END) AS grand_total
FROM table_Name
GROUP BY USER_ID
4

1 回答 1

1

当您询问 oracle 问题时,重要的是要注意版本。在您的情况下-如果您有 11g,则可以查看该pivot功能。

在 10G(和 11g)中,你可以尝试类似的东西

create or replace function get_pivot() 
return sys_refcursor
as
    stmt varchar2(32000);
    c sys_Refcursor;
    cursor c_values as 
        select distinct host from table_name;
begin
    stmt := 'select user_id , ';

    for x in c_values loop
        stmt := stmt || ' sum(case when host = '''||x.host||''' then 1 else 0 end) as ' ||host|| ',';
    end loop;

    stmt := stmt || ' count(host) as grand_total from table_name group by user_id';

    open c for stmt;
    return(c);
end get_pivot;

无论您使用的是数据透视表还是动态 sql,您都必须查询不同的值。

没有测试过 - 我现在没有我的预言机。

于 2013-07-26T13:38:13.430 回答