动态列别名

时间:2014-12-18 06:05:55

标签: sql oracle

我正在寻找一种可以将列别名设置为动态的方法 DDL

CREATE TABLE PRODUCTS
(
PRODUCT_NAME VARCHAR(20),
PRODUCT_PRICE INT );


INSERT INTO PRODUCTS VALUES ('COKE',20);
INSERT INTO PRODUCTS VALUES ('PEPSI',10);
INSERT INTO PRODUCTS VALUES ('FANTA',30);
INSERT INTO PRODUCTS VALUES ('COKE',30);

现在

SELECT SUM(DECODE(PRODUCTS.PRODUCT_NAME,'COKE',PRODUCTS.PRODUCT_PRICE)) AS SSS
FROM PRODUCTS

会导致

SSS
50

SELECT PRODUCT_NAME FROM (SELECT PRODUCT_NAME, ROWNUM AS RANK FROM PRODUCTS 
WHERE ROWNUM = 1)

结果

COKE

我想用可乐代替sss但是从动态的角度来看,如果在数据库中更改了值,那么别名

SELECT SUM(DECODE(PRODUCTS.PRODUCT_NAME,'COKE',PRODUCTS.PRODUCT_PRICE)) AS
(
   SELECT PRODUCT_NAME FROM 
   (SELECT PRODUCT_NAME, ROWNUM AS RANK FROM PRODUCTS WHERE ROWNUM = 1)
)
FROM PRODUCTS

2 个答案:

答案 0 :(得分:2)

您可以使用PIVOT来实现相同目标。

如果要使用子查询而不是Product_name的值  使用PIVOT XML(注意,在这种情况下结果将是XML)

如需了解更多信息,请查看以下链接

PIVOT and UNPIVOT operators in Oracle 11g

with prod as (SELECT PRODUCT_NAME, product_price FROM PRODUCTS)
     select *
     from  prod
     pivot  (sum(product_price) 
            for (product_name) in
            ('COKE' as COKE
          , 'FANTA' as FANTA
          , 'PEPSI' as PEPSI ))

编辑1: - 您也可以只选择下面的特定饮品

     with prod as (SELECT PRODUCT_NAME, product_price FROM PRODUCTS)
     select COKE
     from  prod
     pivot  (sum(product_price) 
            for (product_name) in
            ('COKE' as COKE
          , 'FANTA' as FANTA
          , 'PEPSI' as PEPSI ))

答案 1 :(得分:0)

您必须使用动态查询意味着您创建一个动态语句然后执行。

Here就是一个例子,请使用if else。

对于您的查询更改,请执行此操作。

declare
  l_cursor sys_refcursor;
  sql_query varchar2(4000);
begin
  sql_query := 'select 1 as value from dual';
  open l_cursor for sql_query;
end;

http://docs.oracle.com/cd/E11882_01/appdev.112/e25519/dynamic.htm#LNPLS01102