这是静态数据透视查询:
SELECT
*
FROM
(SELECT
PI.PRODID||' '||' ('||PI.PRODNAME||' - '||PI.PACKSIZE||')' PNAME,I.SIA_ID, IP.SALES_QTY
FROM
DIS_INVOICE_INFO I, DIS_INVOICE_PRODUCT IP, MKT_PROD_INFO PI
WHERE
I.SLNO = IP.SLNO
AND PI.PRODID = IP.PRODID) s
PIVOT
(SUM(SALES_QTY)
FOR SIA_ID IN (10080, 10084, 10082)
) pvt
但是我想要一个动态查询。
赞:
......
PIVOT
(SUM(SALES_QTY)
FOR SIA_ID IN (SELECT DISTINCT SIA_ID FROM DIS_INVOICE_INFO)
) pvt
答案 0 :(得分:0)
您没有提到您的DBMS
,对于其他DBMS
系统我也不知道,但是对于Oracle
,只要您重新产生XML
的结果,如下所示:
SELECT
*
FROM
(SELECT PI.PRODID||' '||' ('||PI.PRODNAME||' - '||PI.PACKSIZE||')' PNAME,
I.SIA_ID, IP.SALES_QTY
FROM DIS_INVOICE_INFO I
INNER JOIN DIS_INVOICE_PRODUCT IP
ON (I.SLNO = IP.SLNO)
INNER JOIN MKT_PROD_INFO PI
ON (PI.PRODID = IP.PRODID)) s
PIVOT XML
(SUM(SALES_QTY)
FOR SIA_ID IN (SELECT DISTINCT SIA_ID FROM DIS_INVOICE_INFO)
) pvt;
通过使用以下DDL
语句;
create table DIS_INVOICE_INFO(SIA_ID int, SLNO int);
create table DIS_INVOICE_PRODUCT(PRODID int, SALES_QTY int, SLNO int);
create table MKT_PROD_INFO(PRODID int,PRODNAME varchar(90),PACKSIZE int);
insert all
into DIS_INVOICE_INFO values(10080,1);
into DIS_INVOICE_PRODUCT values(1,100,1);
into MKT_PROD_INFO values(1,'Milk',200);
select * from dual;
对于上面的SQL-Select
语句,您得到以下结果:
PNAME SIA_ID_XML
------------ ----------
(Milk - 200) <CLOB>
<CLOB>
在哪里
<PivotSet><item><column name = "SIA_ID">10080</column>
<column name = "SUM(SALES_QTY)">100</column></item></PivotSet>
P.s。您不能动态地使用PIVOT
,而没有 XML
选项,这意味着需要像您的情况一样,在IN
子句中明确列出所有参数。