Unpivot or pivot SQL
I have some tables, only one row, but many columns, like this:
Name Null? Type
column1 NUMBER
column2 VARCHAR2(9)
column3 VARCHAR2(9)
column99 VARCHAR2(9)
I want a SQL to generate this kind of result:
Column1 : 1
Column2 : Oracle
Column3 : DB2
Column99 : SQL Server
This SQL could run in 8i,9i,10g and 11g.
Thanks,
In asktom you can search for a function called PRINT_TABLE. I have modified a little to use it as a table function.
drop type table_object
drop type column_object
drop function print_table
create type column_object as object(column_name varchar2(30), column_values varchar2(4000))
create type table_object as table of column_object
create or replace function print_table( p_query in varchar2 ) return table_object pipelined
is
l_theCursor integer default dbms_sql.open_cursor;
l_columnValue varchar2(4000);
l_status integer;
l_descTbl dbms_sql.desc_tab;
l_colCnt number;
begin
execute immediate 'alter session set nls_date_format=''dd-mon-yyyy hh24:mi:ss'' ';
dbms_sql.parse( l_theCursor, p_query, dbms_sql.native );
dbms_sql.describe_columns( l_theCursor, l_colCnt, l_descTbl );
for i in 1 .. l_colCnt loop
dbms_sql.define_column(l_theCursor, i, l_columnValue, 4000);
end loop;
l_status := dbms_sql.execute(l_theCursor);
while ( dbms_sql.fetch_rows(l_theCursor) > 0 ) loop
for i in 1 .. l_colCnt loop
dbms_sql.column_value ( l_theCursor, i, l_columnValue );
pipe row (column_object(l_descTbl(i).col_name,l_columnValue));
end loop;
end loop;
execute immediate 'alter session set nls_date_format=''dd-MON-rr'' ';
return;
exception
when others then
execute immediate 'alter session set nls_date_format=''dd-MON-rr'' ';
raise;
end;
show errSo this would work like this.
SQL> select * from table(print_table('select * from emp'))
2 /
COLUMN_NAME COLUMN_VALUES
EMPNO 1
DEPTNO 1
ENAME Karthick
SAL 80
DOJ 03-dec-2011 04:31:17
JOB
MGR
EMPNO 2
DEPTNO 1
ENAME Karthick_1
SAL 90
DOJ 23-nov-2011 04:31:17
JOB
MGR 1
EMPNO 3
DEPTNO 2
ENAME 1
SAL 80
DOJ 03-dec-2011 04:31:17
JOB
MGR
EMPNO 4
DEPTNO 2
ENAME Ram_1
SAL 90
DOJ 23-nov-2011 04:31:17
JOB
MGR 3
28 rows selected.
SQL>
This SQL could run in 8i,9i,10g and 11g.Oh boy i cant say that :)
Similar Messages
-
Hi again
I need some PIVOT sql help
In this query:
SELECT
SUM([RATES]) as RATES
,SUM([CONVERSION])as CONVERSION
FROM REPORTING
outputs
RATES CONVERSION
23 234
How would change this query to display a table like:
Name Amount
RATES 23
CONVERSION 234
Keep up the good work !nikos101 wrote:
> How would change this query to display a table like:
Do you *HAVE* to change the query... you could just display
it in the
desired format if that it the ultimate and only goal.
<table>
<tr>
<td>name</td>
<td>amount</td>
</tr>
<cfoutput query="sumQry">
<tr><td>Rates</td><td>#rates#</td></tr>
<tr><td>Conversion</td><td>#conversion#</td></tr>
</cfoutput>
</table> -
Pivot sql year/month/category
Need help with this :
Requirement : need to pivot data based on year, month and display the sales correctly. if the data for any month does not exist that month shoudl not appear in the results.
Sample data :
--DROP TABLE APPS.TEST_OM_V CASCADE CONSTRAINTS;
CREATE TABLE APPS.TEST_OM_V
TAX_CATEGORY VARCHAR2(250 BYTE),
SHIP_FROM_ORG_NAME VARCHAR2(100 BYTE),
SCHEDULE_SHIP_DATE DATE,
UNIT_SELLING_PRICE NUMBER,
ORDERED_QUANTITY NUMBER,
INVOICED_SALES NUMBER
Insert into APPS.TEST_OM_V
(TAX_CATEGORY,
SHIP_FROM_ORG_NAME, SCHEDULE_SHIP_DATE, UNIT_SELLING_PRICE, ORDERED_QUANTITY, INVOICED_SALES)
Values
('Operating Supplies', 'DC FONT (FONT-120)', TO_DATE('02/01/2012 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), 12, 13,
23);
Insert into APPS.TEST_OM_V
(TAX_CATEGORY,
SHIP_FROM_ORG_NAME, SCHEDULE_SHIP_DATE, UNIT_SELLING_PRICE, ORDERED_QUANTITY, INVOICED_SALES)
Values
('COFFEE', 'DC CANADA (CAN-180)', TO_DATE('09/30/2011 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), 90, 7,
23.34);
Insert into APPS.TEST_OM_V
(TAX_CATEGORY,
SHIP_FROM_ORG_NAME, SCHEDULE_SHIP_DATE, UNIT_SELLING_PRICE, ORDERED_QUANTITY, INVOICED_SALES)
Values
('COFFEE', 'DC Florida (FLO-180)', TO_DATE('09/14/2011 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), 30, 8,
75);
Insert into APPS.TEST_OM_V
(TAX_CATEGORY,
SHIP_FROM_ORG_NAME, SCHEDULE_SHIP_DATE, UNIT_SELLING_PRICE, ORDERED_QUANTITY, INVOICED_SALES)
Values
('COFFEE', 'DC CANADA (CAN-180)', TO_DATE('10/30/2011 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), 30, 2,
100.11);
Insert into APPS.TEST_OM_V
(TAX_CATEGORY,
SHIP_FROM_ORG_NAME, SCHEDULE_SHIP_DATE, UNIT_SELLING_PRICE, ORDERED_QUANTITY, INVOICED_SALES)
Values
('COFFEE', 'DC CANADA (CAN-180)', TO_DATE('08/30/2011 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), 30, 2,
75);
Insert into APPS.TEST_OM_V
(TAX_CATEGORY,
SHIP_FROM_ORG_NAME, SCHEDULE_SHIP_DATE, UNIT_SELLING_PRICE, ORDERED_QUANTITY, INVOICED_SALES)
Values
('Operating Supplies', 'DC DIST (DIS-130)', TO_DATE('10/21/2011 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), 12, 13,
23);
Insert into APPS.TEST_OM_V
(TAX_CATEGORY,
SHIP_FROM_ORG_NAME, SCHEDULE_SHIP_DATE, UNIT_SELLING_PRICE, ORDERED_QUANTITY, INVOICED_SALES)
Values
('COFFEE', 'DC CANADA (CAN-180)', TO_DATE('08/30/2011 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), 30, 2,
75);
Insert into APPS.TEST_OM_V
(TAX_CATEGORY,
SHIP_FROM_ORG_NAME, SCHEDULE_SHIP_DATE, UNIT_SELLING_PRICE, ORDERED_QUANTITY, INVOICED_SALES)
Values
('Operating Supplies', 'DC CANADA (CAN-180)', TO_DATE('01/02/2012 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), 23, 1,
45);
Insert into APPS.TEST_OM_V
(TAX_CATEGORY,
SHIP_FROM_ORG_NAME, SCHEDULE_SHIP_DATE, UNIT_SELLING_PRICE, ORDERED_QUANTITY, INVOICED_SALES)
Values
('Operating Supplies', 'DC PACK (PK-160)', NULL, 1, 2,
1);
COMMIT;
Expected result , or anything close to this :
2011 2012
AUG SEP OCT JAN FEB UNSCHEDULED
COFFEE
DC CANADA (CAN-180) -30 606.66 -40.11 0 0 0
DC Florida (FLO-180) 0 165 0 0 0 0
Operating Supplies
DC CANADA (CAN-180) 0 0 0 -22 0 0
DC DIST (DIS-130) 0 0 133 0 0 0
DC FONT (FONT-120) 0 0 0 0 133 0
DC PACK (PK-160) 0 0 0 0 0 1 I tried grouping and summing and then lost my way...
select TAX_CATEGORY, SHIP_FROM_ORG_NAME, nvl(TO_CHAR((SCHEDULE_SHIP_DATE), 'MM/YYYY'),'N/A') SCHEDULE_SHIP_DATE,
sum((unit_selling_price * ORDERED_QUANTITY ) - nvl(INVOICED_SALES,0)) CARRYOVER
from XXCNC.TEST_OM_V where 1=1
group by TAX_CATEGORY, SHIP_FROM_ORG_NAME,nvl(TO_CHAR((SCHEDULE_SHIP_DATE), 'MM/YYYY'),'N/A')
order by 1,2,3;
Thanks for your help in advance.
JLike this?:
SQL> set num 6 lin 120 trims on
SQL> col tax_category for a20
SQL> col SHIP_FROM_ORG_NAME for a32
SQL> break on tax_category
SQL> SELECT *
2 FROM (SELECT tax_category,
3 ship_from_org_name,
4 NVL( TO_CHAR( ( schedule_ship_date ), 'MM/YYYY' ), 'N/A' ) schedule_ship_date,
5 ( unit_selling_price * ordered_quantity ) - NVL( invoiced_sales, 0 ) carryover
6 FROM test_om_v) PIVOT (SUM( carryover )
7 FOR schedule_ship_date
8 IN ('08/2011' AS "Aug'11",
9 '09/2011' AS "Sep'11",
10 '10/2011' AS "Oct'11",
11 '11/2011' AS "Nov'11",
12 '12/2011' AS "Dec'11",
13 '01/2012' AS "Jan'12",
14 '02/2012' AS "Feb'12",
15 'N/A' AS "UNSCHEDULED"))
16 ORDER BY 1, 2, 3
17 /
TAX_CATEGORY SHIP_FROM_ORG_NAME Aug'11 Sep'11 Oct'11 Nov'11 Dec'11 Jan'12 Feb'12 UNSCHEDULED
COFFEE DC CANADA (CAN-180) -30 606.66 -40.11
DC Florida (FLO-180) 165
Operating Supplies DC CANADA (CAN-180) -22
DC DIST (DIS-130) 133
DC FONT (FONT-120) 133
DC PACK (PK-160) 1
6 rows selected.:p
Edited by: LKBrwn_DBA on Dec 16, 2011 12:18 PM -
Change multiple column to rows using unpivot or pivot
is there any way I could use pivot or unpivot to get the result show in the graph? From the top table structure to the lower table structure. I could do activity hours and desc separately using unpivot but do not know how to join them together.
Looks like a pivot isn't the best bet, try this:
DECLARE @ActivityReport TABLE ([Employee_ID] [int] NULL, [Week] nvarchar(50) NULL, [Hours_Admin] [float] NULL, [Desc_Admin] [nvarchar](200) NULL, [Hours_HelpDesk] [float] NULL, [Desc_HelpDesk] [nvarchar](200) NULL, [Hours_Support] [float] NULL, [Desc_Support] [nvarchar](200) NULL)
insert into @ActivityReport VALUES (1, 'week1', 5, 'desc', 6, 'desc', 9, 'desc'), (1, 'week2', 5, 'desc1', 6, 'desc1', 9, 'desc1'), (2, 'week1', 5, 'desc', 6, 'desc', 9, 'desc'), (2, 'week2', 5, 'desc2', 6, 'desc2', 9, 'desc2')
SELECT employee_ID, week, hours_admin AS activityHours, 'admin_hours' AS activity_type
FROM @ActivityReport
UNION ALL
SELECT employee_ID, week, hours_helpdesk AS activityHours, 'helpdesk_hours' AS activity_type
FROM @ActivityReport
UNION ALL
SELECT employee_ID, week, hours_support AS activityHours, 'support_hours' AS activity_type
FROM @ActivityReport
ORDER BY Employee_ID, week
Don't forget to mark helpful posts, and answers. It helps others to find relevant posts to the same question. -
Select distinct a.forename as "Name",
a.surname as "Surname",
a.forename ||''||a.surname as "Fullname",
b.ancestors as "Ancestors",
Other columns ..
from table1 a,table2 b,table3 c,table4 d...
where a.col1 =b.col1 and ..(other conditions)
Output is as follows:
Forename1 Surname1 Fullname1 Ancestor1 Other columns
Forename1 Surname1 Fullname1 Ancestor2 Other columns
Forename1 Surname1 Fullname1 Ancestor3 Other columns
Forename1 Surname1 Fullname1 Ancestor4 Other columns
required output is
Forename1 Surname1 Fullname1 Ancestor1/Ancestor2/Ancestor3/Ancestor4 Other columns
I am new to Pivot concept and never used it.
Please help in modifying query.
thanks in advance.The ability to generalise from the specific - in this case the ability to figure out a solution to your problem by examining a solution to someone else's similar problem - is vital in the world of IT.
How about developing your skills in that area by searching the forum for PIVOT or rows+to+columns and see what you can come up with? Even if you can't quite figure it out, we'll be happy to help you over the finish line once you post your query. I suspect that SYS_CONNECT_BY_PATH is actually going to be worth investigating rather than pivot, given your description of the desired output. -
I have requirment to build the SQL to Merge rows value to a single value.
Here is the Data
TABLE_A
ID SEQ MESG
1 1 MSG1
1 2 MSG2
2 1 MSG1
3 1 MSG1
3 2 MSG2
3 3 MSG3
I need output as
ID MSG
1 MSG1 MSG2
2 MSG1
3 MSG1 MSG2 MSG3Create function like below:
CREATE OR REPLACE FUNCTION rowtocol( p_slct IN VARCHAR2, p_dlmtr IN VARCHAR2 DEFAULT ',' ) RETURN VARCHAR2
AUTHID CURRENT_USER AS
TYPE c_refcur IS REF CURSOR;
lc_str VARCHAR2(4000);
lc_colval VARCHAR2(4000);
c_dummy c_refcur;
l number;
BEGIN
OPEN c_dummy FOR p_slct;
LOOP
FETCH c_dummy INTO lc_colval;
EXIT WHEN c_dummy%NOTFOUND;
lc_str := lc_str || p_dlmtr || lc_colval;
END LOOP;
CLOSE c_dummy;
RETURN SUBSTR(lc_str,2);
EXCEPTION
WHEN OTHERS THEN
lc_str := SQLERRM;
IF c_dummy%ISOPEN THEN
CLOSE c_dummy;
END IF;
RETURN lc_str;
END;
/And print result like :
SELECT DISTINCT a.job,
rowtocol( 'SELECT ename FROM emp
WHERE
job = ' || '''' || a.job || '''' || ' ORDER BY ename'
AS Employees
FROM emp; -
Hi Guru's
I have to convert the following format into target table
in the source(oracle) i do have customer address and customer phones tables and i have to load the data by joining on customer_id
i/p
phone_number
123
456
789
o/p
home_phone --- mobile_phone -- work_phone
123 null null
null 456 null
null null 789
the type of the phone is there in type table, depending on the Type_id column with phone(phone.type_id=type.type_id) we will get the type of the phone.
any clues
Thanks
R
Edited by: user11410176 on Aug 10, 2011 11:10 AM
Edited by: user11410176 on Aug 11, 2011 8:07 AMCheck this
Re: How to load Matrix report data into basic table data using ODI
Re: Pivoting in ODI -
I am doing a report for a book store. We have data like:
STORE_ID SUBJECT SUB_DETAIL NUMBERS
1001 CD CD_TITLE1 2
1001 CD CD_TITLE2 4
1001 CD CD_TITLE3 1
1001 DVD DVD_TITLE1 7
1001 DVD DVD_TITLE2 5
1001 DVD DVD_TITLE3 3
1001 DVD DVD_TITLE4 2
1001 BOOK BOOK_TITLE1 6
1001 BOOK BOOK_TITLE2 2
1001 OTHERS OTHERS1 9
1001 OTHERS OTHERS2 1
1001 OTHERS OTHERS3 8
1001 OTHERS OTHERS4 2
1001 OTHERS OTHERS5 3
We want to display the data like:
STORE_ID CD CD_NUM DVD DVD_NUM BOOK BOOK_NUM OTHERS OTHERS_NUM
It can not show the format I want.
Thanks a lot for any help!
Jeannenikos101 wrote:
> How would change this query to display a table like:
Do you *HAVE* to change the query... you could just display
it in the
desired format if that it the ultimate and only goal.
<table>
<tr>
<td>name</td>
<td>amount</td>
</tr>
<cfoutput query="sumQry">
<tr><td>Rates</td><td>#rates#</td></tr>
<tr><td>Conversion</td><td>#conversion#</td></tr>
</cfoutput>
</table> -
Hi,
ID Contract_Year
type1Fee 1
type1Fee 2 type1Fee 3
type2Year1 type2Year2
type2Year3
1 2015
$1.50 $1.50 $1.50
$2.00 $2.00
$2.00
this is my SOURCE DATA, AND i am trying to get in this model
id CONTRACT_yr TYPE
year1 year2 year3
1 2015
type1 1.5
1.5 1.5
2 2015
type2 2.0
2.0 2.0
Please helpHere is the Create table scripts for the above question:
CREATE TABLE fee
Id int
,contracy_yr
int
,type1fee1
money
,type1fee2
money
,type1fee3 money
,type2fee1
money
,type2fee2
money
,type2fee3
money
INSERT INTO fee
SELECT
1,
2015,
$1.5,
$1.5,
$1.5,
$2.0,
$2.0,
$2.0
SELECT * FROM fee
--Expected Output:
SELECT
1 AS id, 2015 AS C_year, 'type1' AS Type,$1.5 AS Fee1,$1.5 AS Fee2,$1.5 AS Fee3
UNION
2 AS id, 2015 AS C_year, 'type2' AS Type,$2.0 AS Fee1,$2.0 AS Fee2,$2.0 AS Fee3 -
Transpose Data in CLR Stored procedure
We have huge data table(600 columns and 800 rows approx) which we want to transpose 600 rows and 800 columns in a CLR stored procedure.
Currently am using a datatable to the transpose. Could anyone suggest any better options other than datatable which gives better performance?Hi Hari,
If my understand is correct, please consider using unpivot or pivot sql:
http://msdn.microsoft.com/en-us/library/ms177410(v=sql.105).aspx
http://blog.sqlauthority.com/2008/06/07/sql-server-pivot-and-unpivot-table-examples/
Best Regards,
Iric
Please remember to mark the replies as answers if they help and unmark them if they provide no help. -
Hello All,
I'm trying to get unpivot and pivot to work and can't quite wrap my head around it.
I created a test table which contains DAY, TYPE, DB_ID. In short the backup schedule for a database instance.
Here is my SQL and output.
select b.day_abbrev, c.bck_type_abbrev
from ori_bck_schedules a
left join ori_days b on b.day_id = a.day_id
left join ori_bck_types c on c.bck_type_id = a.bck_type_id
left join ori_databases d on d.database_id = a.database_id
where a.database_id = 369;
DAY_ABBREV BCK_TYPE_ABBREV
SUN FULL
MON INCR
TUE INCR
WED INCR
THU INCR
FRI INCR
SAT FULL I would like to unpivot this table to get 1 rows showing the day of the weekend and the type of backup? And I ultimately would like to have 1 row showing the day of the week and then just rows showing the DB_ID.
Here is what I mean:
SUN MON TUE WED
DB1 FULL FULL INCR
DB2 INCR INCR FULL
DB3 ......The below code is not working for me.
select b.day_abbrev as "day", c.bck_type_abbrev as "type"
from ori_bck_schedules a
left join ori_days b on b.day_id = a.day_id
left join ori_bck_types c on c.bck_type_id = a.bck_type_id
left join ori_databases d on d.database_id = a.database_id
unpivot (a for day_abbrev in (b.day_abbrev as 'D',c. bck_type_abbrev as 'T'))
ORA-01748: only simple column names allowed here
01748. 00000 - "only simple column names allowed here"
*Cause:
*Action:
Error at Line: 45 Column: 31Can anybody help? Thanks in advance for any assistance
Jantry like this. if you are on 11g
SQL> WITH T
2 AS (SELECT 1 ID, TO_CHAR ( (SYSDATE - 6) + LEVEL, 'DY') day_of_week, 10 * LEVEL expense
3 FROM DUAL
4 CONNECT BY LEVEL <= 7)
5 SELECT *
6 FROM T;
ID DAY EXPENSE
1 SUN 10
1 MON 20
1 TUE 30
1 WED 40
1 THU 50
1 FRI 60
1 SAT 70
7 rows selected.
SQL> WITH T
2 AS (SELECT 1 ID, TO_CHAR ( (SYSDATE - 6) + LEVEL, 'DY') day_of_week, 10 * LEVEL expense
3 FROM DUAL
4 CONNECT BY LEVEL <= 7)
5 SELECT *
6 FROM T PIVOT (MAX (expense)
7 FOR day_of_week
8 IN ('SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT'));
ID 'SUN' 'MON' 'TUE' 'WED' 'THU' 'FRI' 'SAT'
1 10 20 30 40 50 60 70
SQL> on 10g
SQL> WITH T
2 AS (SELECT 1 ID, TO_CHAR ( (SYSDATE - 6) + LEVEL, 'DY') day_of_week, 10 * LEVEL expense
3 FROM DUAL
4 CONNECT BY LEVEL <= 7)
5 SELECT ID,
6 MAX (DECODE (day_of_week, 'SUN', expense)) AS sun,
7 MAX (DECODE (day_of_week, 'MON', expense)) AS mon,
8 MAX (DECODE (day_of_week, 'TUE', expense)) AS tue,
9 MAX (DECODE (day_of_week, 'WED', expense)) AS wed,
10 MAX (DECODE (day_of_week, 'THU', expense)) AS thu,
11 MAX (DECODE (day_of_week, 'FRI', expense)) AS fri,
12 MAX (DECODE (day_of_week, 'SAT', expense)) AS sat
13 FROM T
14 GROUP BY ID;
ID SUN MON TUE WED THU FRI SAT
1 10 20 30 40 50 60 70
SQL> G. -
Are Pivot and Unpivot supported in SSRS
We're upgrading from SSRS 2005 to 2008 R2. I'm rewriting some of my reports and using Unpivot. In SQL it works fine when I run it against the database. But in SSRS (BIDS 2008) when I paste the working SQL statement into the Query Builder, I get
an error that "The UNPIVOT SQL construct or statement is not supported". If i click OK and preview my report, it does run. So, I'm not sure why I'm getting this error. Has anyone had experience with this?
Milissa HartwellThats a known issue with query designer in SSRS. You dont need to worry much on it as report still works fine. If you're so concerned on the pop up make query into a stored procedure and call stored procedure from SSRS dataset query. Then you wont get
any of these issue.
Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs -
Unpivot multiple products fields data dynamically
Hi,
I am having data as below;
ID
CMC
EMS
KBP
Week1
501378
320967
822.54
Week2
13500
6000
3000
Week3
34534
63563
9868
Week4
32523
32532
54223
Week5
235235
53453
34534
Week6
34534
534534
34534
I want to show the above data like below;
Product
Week1
Week2
Week3
Week4
Week5
Week6
CMC
501378
13500
34534
32523
235235
34534
EMS
320967
6000
63563
32532
53453
534534
KBP
822.54
3000
9868
54223
34534
34534
I tried the following query:
declare @ListWeekData varchar(max)
declare @query nvarchar(max)
SET @ListWeekData = STUFF((SELECT distinct ',' + QUOTENAME(convert(varchar,WeekOfMonth))
FROM #WeeklyBreakupData
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
print @ListWeekData
SELECT @query = 'SELECT Product
FROM
#WeeklyBreakupData
UNPIVOT
Producta FOR Product IN (' + STUFF(@ListWeekData, 1, 1, '') + ')
) AS up;';
PRINT @query;
EXEC (@query);
drop table #WeeklyBreakupData
but unable to get the desired result. Please help me out ASAP.
Thanks,
SriniHere you go
CREATE TABLE tmp (Name CHAR(1),Forecast INT,Stock INT)
INSERT tmp SELECT 'a',100,300
INSERT tmp SELECT 'b',300,400
INSERT tmp SELECT 'c',200,250
INSERT tmp SELECT 'd',200,300
-- dynamic pivot (SQL Server 2005/2008)
DECLARE @pivot_cols NVARCHAR(1000);
SELECT @pivot_cols =
STUFF((SELECT DISTINCT '],[' + Name
FROM tmp
ORDER BY '],[' + Name
FOR XML PATH('')
), 1, 2, '') + ']';
DECLARE @pivot_query NVARCHAR(2000);
SET @pivot_query =
N'SELECT * FROM (
SELECT * FROM (
SELECT Name,SUM(Forecast) Forecast,SUM(Stock) Stock FROM tmp
GROUP BY Name ) tmp UNPIVOT
Col for [GROUP] IN (Forecast,Stock)
) as UnPvt ) pvt
PIVOT (MAX(Col) FOR Name IN (' + @pivot_cols + ')) j'
EXEC(@pivot_query);
Best Regards,Uri Dimant SQL Server MVP,
http://sqlblog.com/blogs/uri_dimant/
MS SQL optimization: MS SQL Development and Optimization
MS SQL Consulting:
Large scale of database and data cleansing
Remote DBA Services:
Improves MS SQL Database Performance
SQL Server Integration Services:
Business Intelligence -
Hello folks,
Cant find any artice on what is better to use unpivot or union all. I can achive same results using either but cant decide what would be better. For example a table has columns:
Name 1, Phone1, Name 2, Phone 2. The result I want would be:
Name 1, Phone 1
Name 2, Phone 2.
Best regards,
IgorUsing an unpivot type query would only access the table once while a union would access it twice in your example, so I would go for the unpivot myself.
SQL> with pivoter as (
2 select 1 occ from dual union all
3 select 2 from dual)
4 select case when occ = 1 then name1 else name2 end name,
5 case when occ = 1 then phone1 else phone2 end phone
6 from t
7 cross join pivoter;
Execution Plan
Plan hash value: 1330849661
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
| 0 | SELECT STATEMENT | | 4 | 124 | 8 (0)| 00:00:01 |
| 1 | MERGE JOIN CARTESIAN| | 4 | 124 | 8 (0)| 00:00:01 |
| 2 | VIEW | | 2 | 6 | 4 (0)| 00:00:01 |
| 3 | UNION-ALL | | | | | |
| 4 | FAST DUAL | | 1 | | 2 (0)| 00:00:01 |
| 5 | FAST DUAL | | 1 | | 2 (0)| 00:00:01 |
| 6 | BUFFER SORT | | 2 | 56 | 8 (0)| 00:00:01 |
| 7 | TABLE ACCESS FULL | T | 2 | 56 | 2 (0)| 00:00:01 |
SQL> select name1, phone1 from t
2 union all
3 select name2, phone2 from t;
Execution Plan
Plan hash value: 663398312
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
| 0 | SELECT STATEMENT | | 4 | 56 | 6 (50)| 00:00:01 |
| 1 | UNION-ALL | | | | | |
| 2 | TABLE ACCESS FULL| T | 2 | 28 | 3 (0)| 00:00:01 |
| 3 | TABLE ACCESS FULL| T | 2 | 28 | 3 (0)| 00:00:01 |
---------------------------------------------------------------------------John
Edited by: John Spencer on Dec 11, 2012 9:43 AM
Added example -
Hi all,
One thing i'm struggling with is the use of the pivot function to pivot a column within PQ. I'm confused on why this happens and why I can't clear it up...but here goes:
I unpivot a set of columns which then gives me two columns (Attribute/Value). I do this because I have repeated columns of data, but it should all fall under one column (think Hours, Hours1, Hours2, etc) - basically the input is coming from a form
that has repeating fields but everything is the same data type.
I make some adjustments to the Attribute columns (Replace items within the Attribute column) then Pivot the two columns again...theoretically I would be able to do this since i just unpivoted the same data, but:
I get tons of errors (usually "There were too many elements in the enumeration to complete the operation".). I'm not entirely sure why this happens and it doesn't seem to make sense to me that I can't UnPivot and Pivot and get the same results
as I originally had.
Any recommendations would be greatly appreciated!
EDIT: I'm choosing "don't aggregate" during the Pivot operation...I get values if I keep some sort of aggregate function, but not the right values (I get a count of the fields instead of the data within the fields)Try this solution:
Once you are to step 3, add an index column that starts at 0 and another index column that starts at 1.
Transform by Pivot Column using the names in Attribute to create new columns and the Values Column set to Value. Under advanced options select Don't Aggregate.
Fill Down the Date column
Filter rows to remove null from Work Time.
Here's the M code from the advanced editor:
let
Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
#"Added Index" = Table.AddIndexColumn(Source, "Index", 0, 1),
#"Added Index1" = Table.AddIndexColumn(#"Added Index", "Index.1", 1, 1),
#"Pivoted Column" = Table.Pivot(#"Added Index1", List.Distinct(#"Added Index1"[Attribute]), "Attribute", "Value"),
#"Filled Down" = Table.FillDown(#"Pivoted Column",{"Date"}),
#"Filtered Rows" = Table.SelectRows(#"Filled Down", each ([Work Time] <> null)),
#"Changed Type" = Table.TransformColumnTypes(#"Filtered Rows",{{"Work Time", type time}})
in
#"Changed Type"
If that doesn't work, this example might do the trick:
http://www.excelguru.ca/blog/2015/01/07/transpose-stacked-tables/
Maybe you are looking for
-
Hi, i am very very stuck in adding a image to a JPanel. here is my code could any one please show me where and how to add an image to this please. a sample code would be prefered. Thanks * card.java public class card extends javax.swing.JFrame { /**
-
Dynamic commandline parameters
Greetings, I have developed a custom client side application that is used to upload a data file to a servlet and have the servlet convert the document to an internal data format and send back the file name to the client. The client then uses this fil
-
Changing Subject: Header for bounced messages
Our current version: imsimta version Sun Java(tm) System Messaging Server 7.0-3.01 64bit (built Dec 9 2008) libimta.so 7.0-3.01 64bit (built 09:24:13, Dec 9 2008) Using /opt/sun/comms/messaging64/config/imta.cnf SunOS mmp-nhm1.its.utas.edu.au 5.10 Ge
-
When I am trying to save pictures, I am having problems... When I check the jpeg box, it trys and saves the file as a pdf file, when I tried tiff, it tired to save the file as a dicom file??? anyone else having this problem???? The only function that
-
Icloud app does not load when I open outlook
I installed control panel & set it up for outlook. when I open outlook I have to manually start Icloud add in. shows add in as inactive in "file"/ "options"/. I have uninstalled/re-installed icloud which hasn't made a difference.