Pivoting data
Hi, I'm hoping someone can point me in the right direction...
I need to create a report that pivots data, however I'm struggling to get the resultset I'm looking for. I need to display the data below:
MANAGER U_ID A B C
1703 1703 3 3 1
1703 1702 1 1 1
1703 1701 0 2 0
like so: MANAGER U_ID
sum of A 4 3
sum of B 6 1
sum of C 2 1
Hope that makes sense. Any help is really appreciated.
Thanks
Hi,
Andyindo wrote:
Hi, I'm hoping someone can point me in the right direction...
I need to create a report that pivots data, however I'm struggling to get the resultset I'm looking for. I need to display the data below:
MANAGER U_ID A B C
1703 1703 3 3 1
1703 1702 1 1 1
1703 1701 0 2 0
like so: MANAGER U_ID
sum of A 4 3
sum of B 6 1
sum of C 2 1You may have noticed that this site normally doesn't display multiple spaces in a row.
Whenever you post formatted text (such as query results) on this site, type these 6 characters:
\(small letters only, inside curly brackets) before and after each section of formatted text, to preserve spacing.
Hope that makes sense. Any help is really appreciated.It looks like you want to pivot and unpivot in the same query.
The following thread has an example of how to do that:
Re: Help with PIVOT query (or advice on best way to do this)
Whenever you have a question, post CREATE TABLE and INSERT statements for the sample data, and explain how you get the results you want from that data. I can guess at what the next-to-last column of output is, but guessing isn't a very good way to solve problems, and might not be as accurate as what you know. What does the last column of output mean? How do you get those numbers, 3, 1 and 1?
Similar Messages
-
Trouble writing Query for Pivoting data from a table
I am having a little trouble writing a query for converting the below table data into a pivot data. I am trying to write a query for which if I give a single valid report_week date as input it should give me the data for that week and also provide two extra columns, one which gives the data of last week for the same countries and the second column which gives the difference of numbers in both the columns(i.e. COUNT - COUNT_LAST_WEEK).
REPORT_WEEK DIVISION COUNT
9/26/2009 country1 81
9/26/2009 country2 97
9/26/2009 country3 12
9/26/2009 country4 26
9/26/2009 country5 101
10/3/2009 country1 85
10/3/2009 country2 98
10/3/2009 country3 10
10/3/2009 country4 24
10/3/2009 country5 101
10/10/2009 country1 84
10/10/2009 country2 98
10/10/2009 country3 10
10/10/2009 country4 25
10/10/2009 country5 102
For example, if I give input as 10/10/2009, the output should be as give below.
REPORT_WEEK DIVISION COUNT COUNT_LAST_WEEK DIFFERENCE
10/10/2009 country1 84 85 -1
10/10/2009 country2 98 98 0
10/10/2009 country3 10 10 0
10/10/2009 country4 25 24 1
10/10/2009 country5 102 101 1
For example, if I give input as 10/3/2009, the output should be as give below.
REPORT_WEEK DIVISION COUNT COUNT_LAST_WEEK DIFFERENCE
10/3/2009 country1 85 81 4
10/3/2009 country2 98 97 1
10/3/2009 country3 10 12 -2
10/3/2009 country4 24 26 -2
10/3/2009 country5 101 101 0
Can anyone please shed some light on Query building for the above scenarios.
Thank you
SKP
Edited by: user11343284 on Oct 10, 2009 7:53 AM
Edited by: user11343284 on Oct 10, 2009 8:28 AMI assume there is no gap in report weeks. If so:
SQL> variable report_week varchar2(10)
SQL> exec :report_week := '10/10/2009'
PL/SQL procedure successfully completed.
with t as (
select to_date('9/26/2009','mm/dd/yyyy') report_week,'country1' division,81 cnt from dual union all
select to_date('9/26/2009','mm/dd/yyyy'),'country2',97 from dual union all
select to_date('9/26/2009','mm/dd/yyyy'),'country3',12 from dual union all
select to_date('9/26/2009','mm/dd/yyyy'),'country4',26 from dual union all
select to_date('9/26/2009','mm/dd/yyyy'),'country5',101 from dual union all
select to_date('10/3/2009','mm/dd/yyyy'),'country1',85 from dual union all
select to_date('10/3/2009','mm/dd/yyyy'),'country2',98 from dual union all
select to_date('10/3/2009','mm/dd/yyyy'),'country3',10 from dual union all
select to_date('10/3/2009','mm/dd/yyyy'),'country4',24 from dual union all
select to_date('10/3/2009','mm/dd/yyyy'),'country5',101 from dual union all
select to_date('10/10/2009','mm/dd/yyyy'),'country1',84 from dual union all
select to_date('10/10/2009','mm/dd/yyyy'),'country2',98 from dual union all
select to_date('10/10/2009','mm/dd/yyyy'),'country3',10 from dual union all
select to_date('10/10/2009','mm/dd/yyyy'),'country4',25 from dual union all
select to_date('10/10/2009','mm/dd/yyyy'),'country5',102 from dual
select max(report_week) report_week,
division,
max(cnt) keep(dense_rank last order by report_week) cnt_this_week,
max(cnt) keep(dense_rank first order by report_week) cnt_last_week,
max(cnt) keep(dense_rank last order by report_week) - max(cnt) keep(dense_rank first order by report_week) difference
from t
where report_week in (to_date(:report_week,'mm/dd/yyyy'),to_date(:report_week,'mm/dd/yyyy') - 7)
group by division
order by division
REPORT_WE DIVISION CNT_THIS_WEEK CNT_LAST_WEEK DIFFERENCE
10-OCT-09 country1 84 85 -1
10-OCT-09 country2 98 98 0
10-OCT-09 country3 10 10 0
10-OCT-09 country4 25 24 1
10-OCT-09 country5 102 101 1
SQL> exec :report_week := '10/3/2009'
PL/SQL procedure successfully completed.
SQL> /
REPORT_WE DIVISION CNT_THIS_WEEK CNT_LAST_WEEK DIFFERENCE
03-OCT-09 country1 85 81 4
03-OCT-09 country2 98 97 1
03-OCT-09 country3 10 12 -2
03-OCT-09 country4 24 26 -2
03-OCT-09 country5 101 101 0
SQL> SY. -
Hi Gurus
I need to pivot data by merging 2 rows into 1. ie.
Notif Group Code
1 AS 01
1 EF 05
2 AS 02
3 EF 07
Result is
Notif AS_Code EF_Code
1 01 05
2 02 ?
3 ? 07
As you can see if either the AS or EF code is missing for a given notification then it it is set as unknown (question mark etc).
My first attemp was to use formulas in the transformation. ie. (IF Group = AS, Code, ?) for the AS_Code field and a similar formula for the EF_Code field. However, this only works for notifs 2 and 3. For Notif 1 one of the values is always ? when both should have a value.
Ideally what I need to be able to do is check the vlaues of the target fields and if they are not set then set them to ?. Is this possible ? How do I access access target fields ?
Any other options also appreciated.
Thanx
Hong Kong FueyHi Prafulla
Sorry, I think my post is a little confusing. The result is the desired result but I am not acheiving it.
The 2 and the 3 relate to different notifications (ie. Key field) They shouldnt be changed. These records are not causing me any problems.
The two notification 1 records are getting merged but the result is wrong ie.
Notif AS_code EF_Code
1 ? 05
The ? should be 01.
regards
Asif -
Hi Everyone,
I have an interesting challenge which involves extracting data from two related databases, and pivoting part of the data from the second.
Where I work we use SAP Business One (ERP) in concert with Accellos (WMS). Within our Warehouses we store items in many bin locations. Bin locations; items in those locations, along with quantities, etc are stored in the Accellos database. Master data related
to the items themselves, such as the item cost, preferred supplier, etc is stored in SAP Business One.
Whilst I have been able to create reports which successfully bridge both SAP & Accellos, such as that shown below, I have not been able to present the data output in an ideal format.
As can be seen above given a single item code (e.g.: DR1124) there are many bin labels (and corresponding quantities) returned.
I would like to show the bin labels 'horizontally' in the fashion illustrated below -
I believe that using a Pivot is pivotal (excuse the pun!) to success in my endeavour, and due to this I have studied up on Pivots, both the Static type (which I am now comfortable with) and the Dynamic type (which I am still getting 'my head around').
However there are a couple of challenges related to my specific pivot.
The maximum number of Bins (and correspondingly Bin Labels) per Item change
There are over 10K Bin Labels
I have written a basic Dynamic Pivot which shows all Bin Labels horizontally, like so...
DECLARE @SQL nvarchar(max), @Columns nvarchar(max)
SELECT @Columns =
COALESCE(@Columns + ', ', '') + QUOTENAME(BINLABEL)
FROM
SELECT DISTINCT
BINLABEL
FROM A1Warehouse..BINLOCAT
) AS B
ORDER BY B.BINLABEL
SET @SQL = '
WITH PivotData AS
SELECT
BINLABEL
, PRODUCT
, QUANTITY
FROM A1Warehouse..BINLOCAT
SELECT
PRODUCT,
'+ @Columns +'
FROM PivotData
PIVOT
SUM(QUANTITY)
FOR BINLABEL
IN('+ @Columns +')
) AS PivotResult'
EXEC(@SQL)
The above technique gives me over 10K columns because there are that many Bin Labels in total.
It occurred to me that I would need to count the maximum number of Bin Labels for the Item that had the most Bin Labels, and that this number would then need to be used to set the maximum number of columns.
DECLARE @maxBins int
DECLARE @loopCount int = 1
SET @maxBins = (SELECT MAX([# of Bins]) AS 'Max Bins'
FROM
SELECT
COUNT(BINLABEL) '# of Bins'
FROM A1Warehouse..BINLOCAT
GROUP BY PRODUCT
) AS T0)
PRINT @maxBins
At this point in time one item occupies a total of 26 bin labels / locations. Every other item occupies less than 26 bin labels / locations, so I now know that I need to number my vertical columns as 'Bin 1', 'Bin 2', 'Bin 3', 'Bin...', 'Bin 26'.
This is where the fun starts, I don't exactly need a Dynamic Pivot, but neither is a Static Pivot up to the task (at least not as best I can tell).
Here is the Static Pivot query that I have written -
DECLARE @fromDate DATE = DATEADD(YY, -1, GETDATE())
DECLARE @toDate DATE = GETDATE()
DECLARE @maxBins int
DECLARE @loopCount int = 1
SET @maxBins = (SELECT MAX([# of Bins]) AS 'Max Bins'
FROM
SELECT
COUNT(BINLABEL) '# of Bins'
FROM A1Warehouse..BINLOCAT
GROUP BY PRODUCT
) AS T0)
PRINT @maxBins
SELECT *
FROM
SELECT
Tx.[Item Code]
, Tx.Description
, SUM(Tx.[Sales (last 12 Months)]) AS 'Sales (last 12 Months)'
, ISNULL(Tx.[Supplier Code], '') AS 'Supplier Code'
, ISNULL(Tx.[Supplier Name], '') AS 'Supplier Name'
, Tx.OnOrder
, Tx.IsCommited
, Tx.OnHand
, ISNULL(Tx.BINLABEL, '') AS 'Binlabel'
, ISNULL(CAST(Tx.QUANTITY AS nvarchar), '') AS 'Quantity'
FROM
SELECT
T0.ItemCode AS 'Item Code'
, T0.Dscription AS 'Description'
, SUM(T0.Quantity) AS 'Sales (last 12 Months)'
, T3.CardCode AS 'Supplier Code'
, T3.CardName AS 'Supplier Name'
, T2.OnOrder
, T2.IsCommited
, T2.OnHand
, T4.BINLABEL
, T4.QUANTITY
FROM INV1 T0
INNER JOIN OINV T1 ON T1.DocEntry = T0.DocEntry AND T1.CANCELED = 'N'
INNER JOIN OITM T2 ON T2.ItemCode = T0.ItemCode
LEFT JOIN OCRD T3 ON T3.CardCode = T2.CardCode
LEFT JOIN A1Warehouse..BINLOCAT T4 ON T4.PRODUCT = T0.ItemCode collate SQL_Latin1_General_CP850_CI_AS
WHERE T1.DocDate >= @fromDate AND T1.DocDate <= @toDate
GROUP BY T0.ItemCode, T0.Dscription, T3.CardCode, T3.CardName, T2.OnOrder, T2.IsCommited, T2.OnHand, T4.BINLABEL, T4.QUANTITY
UNION ALL
SELECT
T0.ItemCode AS 'Item Code'
, T0.Dscription AS 'Description'
, -SUM(T0.Quantity) AS 'Sales (last 12 Months)'
, T3.CardCode AS 'Supplier Code'
, T3.CardName AS 'Supplier Name'
, T2.OnOrder
, T2.IsCommited
, T2.OnHand
, T4.BINLABEL
, T4.QUANTITY
FROM RIN1 T0
INNER JOIN ORIN T1 ON T1.DocEntry = T0.DocEntry
INNER JOIN OITM T2 ON T2.ItemCode = T0.ItemCode
LEFT JOIN OCRD T3 ON T3.CardCode = T2.CardCode
LEFT JOIN A1Warehouse..BINLOCAT T4 ON T4.PRODUCT = T0.ItemCode collate SQL_Latin1_General_CP850_CI_AS
WHERE T1.DocDate >= @fromDate AND T1.DocDate <= @toDate
GROUP BY T0.ItemCode, T0.Dscription, T3.CardCode, T3.CardName, T2.OnOrder, T2.IsCommited, T2.OnHand, T4.BINLABEL, T4.QUANTITY
)Tx
GROUP BY Tx.[Item Code], Tx.Description, Tx.[Supplier Code], Tx.[Supplier Code], Tx.[Supplier Name], Tx.OnOrder, Tx.IsCommited, Tx.OnHand, Tx.BINLABEL, Tx.QUANTITY
)Ty
PIVOT
MAX(Ty.Quantity)
FOR Ty.Binlabel IN ([0], [1], [2])
)Tz
Here is a screen shot of the results that I see -
I understand why there are NULLs in my 0, 1, and 2 columns...there simply aren't Bin Labels called 0, 1 or 2!
My challenge is that I do not know how to proceed from here. Firstly how do I call each of the pivoted columns 'Bin 1', 'Bin 2', 'Bin...', 'Bin 26' when the actual Bin Labels are over 10 thousand different possible character sets, e.g.: #0005540, K1C0102, etc,
etc, etc...
I have considered the possibility that a WHILE loop may be able to serve in populating the column names...
DECLARE @maxBins int
DECLARE @loopCount int = 1
SET @maxBins = (SELECT MAX([# of Bins]) AS 'Max Bins'
FROM
SELECT
COUNT(BINLABEL) '# of Bins'
FROM A1Warehouse..BINLOCAT
GROUP BY PRODUCT
) AS T0)
PRINT @maxBins
WHILE @loopCount <= @maxBins
BEGIN
PRINT @loopCount
SET @loopCount = @loopCount +1
END
...of course the query above has no practical application at this stage, but I thought that it may be useful
from a 'logic' point of view.
I have tried to insert a WHILE clause into various locations within the Static Pivot query that I wrote, however in each instance there were errors produced by SSMS.
If anybody can suggest a way to solve my data pivoting challenge it will be much appreciated.
Kind Regards,
DavidHow you can 'assign' multiple values to the @SQL variable (if that is indeed what is happening)
What 'FOR XML PATH('') actually does
Dynamic SQL in general...
if you could share some insights into how I can go about removing the NULLs it will be greatly appreciated.
The FOR XML PATH('') method is one of several ways to concatenate the values from several rows into one column of one row. There are other ways, but I believe the most commonly used one today (and certainly the one I always use) is the FOR XML method.
A good link for understanding the FOR XML method is
http://bradsruminations.blogspot.com/2009/10/making-list-and-checking-it-twice.html.
If you are not used to dynamic SQL, there is an excellent discussion at http://www.sommarskog.se/dynamic_sql.html. If you are not used to dynamic SQL, you definitely want to review the SQL Injection topic on that page before making extensive use of
dynamic SQL.
You can get rid of the NULLs, but only by converting the NULLs into a value. You can use the IsNull() function or as diadmin noted the Coalesce() function to do this. There is, however, the question of what value do you want. Of course
the obvious choice for converting varchar values (like BinLabel) is the empty string (''). But for numeric values (like BinQty) you need to either output a number (like 0.000000) or you need to convert the numbers into a character type and then you could
use the empty string. Of course doing this makes this already complex piece of SQL more complex, but it certainly can be done. An example
Create Table Foo(ItemCode varchar(6), ItemDescription varchar(50), OrderQty decimal(12,6), BinLabel varchar(7), BinQty decimal(12,6));
Insert Foo(ItemCode, ItemDescription, OrderQty, BinLabel, BinQty) Values
('DR1124', 'D6 Series 24 OD 3/8 1 Neck', 50, 'B1A1904', 9),
('DR1124', 'D6 Series 24 OD 3/8 1 Neck', 50, 'M1D0703', 66),
('DR1124', 'D6 Series 24 OD 3/8 1 Neck', 50, 'S1K0603', 24),
('H21', 'Rubber Mallot', 75, 'X1X0712', 100),
('H21', 'Rubber Mallot', 75, 'T3B4567', 92);
Declare @SQL nvarchar(max);
;With cteRN As
(Select ItemCode, ItemDescription, BinLabel, BinQty,
Row_Number() Over(Partition By ItemCode Order By BinLabel) As rn
From Foo)
Select @SQL = (Select Cast(N'' As nvarchar(max)) + N', IsNull(Max(Case When rn = ' + Cast(rn As nvarchar(5)) + N' Then BinLabel End), '''') As BinLabel' + Cast(rn As nvarchar(5))
+ N', IsNull(Cast(Max(Case When rn = ' + Cast(rn As nvarchar(5)) + N' Then BinQty End) As varchar(19)), '''') As BinQty' + Cast(rn As nvarchar(5))
From (Select Distinct rn From cteRN) x
Order By rn
For XML Path(''))
Select @SQL = Stuff(@SQL, 1, 2, '');
--Select @SQL
Select @SQL = N'Select ItemCode, Max(ItemDescription) As ItemDescription, Max(OrderQty) As OrderQty,' + @SQL + N' From (Select ItemCode, ItemDescription, OrderQty, BinLabel, BinQty,
Row_Number() Over(Partition By ItemCode Order By BinLabel) As rn
From Foo) As x Group By ItemCode'
--select @SQL
Exec(@SQL);
-- Cleanup
go
Drop Table Foo;
Tom -
Pivoting date data in Diadem - summarising data by grouping
Hi,
Is there a way to summarise date data in Diadem?
For example, if I have a file with the following headings:
Date/time, on/off, duration
The Date/time column is recordrded in date, hours and seconds,
the on/off is either 1 or 0
duration is the difference in time values when on/off is 1.
Is there a way to summarise the date data by day or possibly by month? (The corresponding numbers in 'duration' would need to be assigned to the appropriate day or month)?
The equivalent calculation tool would be a pivot table in Excel.
Look foward to a response.Hi Brad,
Thank you for your prompt response.
I have attached a file in the code section with some data. (Apologies for this, but the NI website said the content did not match the filetype). (I will try and get this right and send the attachement as an excel file. DIADEM should be able to read in the text file).
The columns are as follows: Event, Date,Time,Duration On,State.
(please note 1) that in the 'event' column there are 5 boilers - good for pivoting once grouped per boiler,
2) that 'State' is either a save or a bypass - also good for pivoting i.e. which days and boilers were in bypass, and which days and boilers were in save)
I would like to be able to summarise the data as follows:
Show a period(group by month or year) the sum of the Duration On, then display the result on a monthly histogram showing for example daily Duration On vs date.
Then
on an annual histogram showing for example monthly Duration On vs month.
As the last part of the exercise, how can I break out doing the 2 steps about for each of the 5 seperate boilers and show when each of the boilers were in a save or a bypass?
(Is a pivot table in excel required or can all the data processing be done in DIADEM?)
I appreciate your assistance in resolving this issue.
Sincerely
HotCold
Attachments:
Heathrow.txt 442 KB -
Power Pivot Data Model with Linked Table
Can anyone provide me with some suggestions as to how to accomplish the following in Power Pivot?
I have the following Pivot Table fields. I'm trying to create a data model to allow me to filter all of the projects by the selected Fiscal Year. The Fiscal Year table is a dimension I created to group the data by.
I'm considering separating Projects into multiple tables such that 1 table is for Year1 information, another table is for Year2 information (includes Year2FiscalYear, Year2BudgetCAP, etc.).
I think what I need to do is create a measure to allow me to filter the records by fiscal year. Anyone have any ideas?
Thanks,
RolandHi Greg,
The data is coming from Project Online (OData feed) and SharePoint lists (all within Project Online). I'm creating an Excel Report.
The reason I can't use Power Query is because refreshing a report that is built using Power Query is not supported via browser. Power BI is needed to do this. On the other hand if I build an excel report using Power Pivot only, the browser refresh functionality
works.
The Year1FiscalYear, Year2FiscalYear, etc. are all enterprise custom fields in Project Online. Therefore I have some control in being able to change the format of the data. I'm looking into what are some options on my side to configure Project Online or
SharePoint lists to make building the model simpler...
Thanks,
Roland -
Best practises for using Excel functions on Power Pivot Data
Hi
How do you suggest to perform calculations on cells in a power pivot table? Obviously the ideal approach is to use a DAX measure. But given that DAX doesn't have every function, is there a recommended way of eg adding an "extra" ( ie just
adjacent) column to a pivot table. ( in particular I want to use beta.inv )
I could imagine one option of adding some VBA that would update the extra column as the pivot table itself refreshed ( and added more/less rows)
thanks
seanHi Sean,
I don't know what's your expected requirement regarding this issue, maybe you can share some sample data or scenario to us for further investigation. As we know, if we need to add extra column to PowerPivot data model, we can directly
create a calcuated column:
calculated columns:
http://www.powerpivot-info.com/post/178-how-to-add-dax-calculations-to-the-powerpivot-workbooks
There are some different between Excel and DAX functions, here are the list for your reference:
Excel functions (by category):
http://office.microsoft.com/en-us/excel-help/excel-functions-by-category-HA102752955.aspx
DAX Function Reference:
http://msdn.microsoft.com/en-us/library/ee634396.aspx
Hope this helps.
Regards,
Elvis Long
TechNet Community Support -
How to seperate Power Pivot Data Model and Power Pivot Report from Single Workbook.
HI Team,
Initially, We have created Power Pivot report in workbook, containing Source Data Model as well.
Now, we want to convert workbook having model as Shared Data Model, and all report needs to be part of single workbook.
I want to implement one of the below solution, but know how to do it.
1. Separate and Export all Power Pivot report sheet into single Excel Workbook such that it will have all report sheets.
2. Use Same Model as it is and delete reports from existing one after export to new excel workbook.
OR
Is there is any other way to avoid re-creation of reports again? I want to use same report but instead of Embedded Excel data source, I want to use shared data Source in excel.One option is to use one workbook as the data source(model) and other workbooks for the reports. This works in the stand alone Excel and SharePoint versions of Power BI, but not yet in O365 Power BI version.
There is no export functionality. You would have to copy the workbook and update data source references. I have never tried it, but in theory it should work :).
Brad Syputa, Microsoft Reporting Services This posting is provided "AS IS" with no warranties.
Hi Michael,
Yes your answer is partially correct..thanks for reply, I am working on Power Pivot reports on SharePoint.
However, below issues observed.
1. There is No Export Functionality ( as you told)
2. We can not copy report sheet from workbook1 (which has Data Model) to Workbook2 ( only for report) using Control + C (copy) and Control + V (paste) option.
Or Move Power Pivot Table ..
So, solution can be (as you said, unfortunately I tried it already but dint worked)
1. Copied workbook with New Name - Workbook2.
2. Go to Data -> I tried to change connection setting -> to use shared Data Model -> I could create new Pivot table using shared Data Model
But, Still I could use earlier designed Power Pivot tables as it is, to point to shared data model.
I don't want to re-design entire report. As my project workbook has plenty reports.... :) -
Hi all,
I'm trying to use a PIVOT on the following data set:
ID STATUS_DESC PAY_STATUS PAID_DATE TRANSACTION_TYPE TRANSACTION_DESC DEBIT TOTAL
9876 In Progress 2nd Payment Made 11-DEC-12 19.38.57 Card Payment Payment 2 349 349
9876 In Progress 2nd Payment Made 06-DEC-12 14.33.57 Card Payment Payment 1 100 100
However I'm still getting two rows as per the below. Ideally all data should be on a single row.
ID STATUS_DESC PAY_STATUS PAYMENT_1_DATE PAYMENT_1_AMT PAYMENT_2_DATE PAYMENT_2_AMT TOTAL
9876 In Progress 2nd Payment Made 06-DEC-12 14.33.57 100 100
9876 In Progress 2nd Payment Made 11-DEC-12 19.38.57 349 349
I have constructed my pivot using the following on the outer select:
PIVOT (MAX (insert_timestamp) AS paid_date
,SUM (debit) AS amt
FOR transaction_desc IN ('Payment 1' AS payment_1,
'Payment 2' AS payment_2)) ;
I've used MAX to pivot the date and also tried using NVL on the insert_timestamp but still no luck.
Any ideas?
Thank you in advance.
Edited by: Brian1982 on Jan 28, 2013 3:43 PMBrian1982 wrote:
My desired output would be a single row.
with t as (
select 9876 id,'In Progress' status_desc,'2nd Payment Made' pay_status,to_date('11-DEC-12 19.38.57','dd-mon-rr hh24.mi.ss') paid_date,'Card Payment' transaction_type,'Payment 2' transaction_desc,349 debit,349 total from dual union all
select 9876,'In Progress','2nd Payment Made',to_date('06-DEC-12 14.33.57','dd-mon-rr hh24.mi.ss'),'Card Payment','Payment 1',100,100 from dual
select payment_1_id id,
payment_1_status_desc status_desc,
payment_1_pay_status pay_status,
payment_1_dt,
payment_1_amt,
payment_2_dt,
payment_2_amt
from t
pivot(
max(id) id,
max(status_desc) status_desc,
max(pay_status) pay_status,
max(paid_date) dt,
max(transaction_type) transaction_type,
max(debit) amt,
max(total) total
for transaction_desc in ('Payment 1' AS payment_1,'Payment 2' AS payment_2)
ID STATUS_DESC PAY_STATUS PAYMENT_1_DT PAYMENT_1_AMT PAYMENT_2_DT PAYMENT_2_AMT
9876 In Progress 2nd Payment Made 06-dec-12 14.33.57 100 11-dec-12 19.38.57 349
SQL> SY. -
I have a table that contains the following fields:
FORM_TYPE___FORM_YEAR___LINE_ITEM___BUCKET
-----DW23----------- 2008----------------1-------------34
-----DW23----------- 2008----------------11------------12
-----DW23----------- 2008----------------87------------16
-----DW23----------- 2008----------------14------------3
For the data above, I am trying to output each LINE_ITEM as a column, with the corresponding BUCKET as the data, like so:
FORM_TYPE____FORM_YEAR______1_____11____87____14
----DW23-----------2008----------------34-------12-----16-------3
I am running on 11g, so I read about the PIVOT function, but you can only use it on aggregate data (if I am understanding the documentation). Does anyone have any suggestions on accomplishing this?
Thanks,
David
Edited by: 930209 on May 10, 2012 7:49 AMHi,
Learning from there : {message:id=9360005}
I come to this :Scott@my11g SQL>with t(FORM_TYPE,FORM_YEAR,LINE_ITEM,BUCKET)
2 as (
3 select 'DW23','2008',1,34 from dual
4 union all select 'DW23','2008',11,12 from dual
5 union all select 'DW23','2008',87,16 from dual
6 union all select 'DW23','2008',14,3 from dual
7 )
8 select *
9 from t
10 pivot(
11 max(bucket)
12 for line_item in (1,11,87,14)
13 ) ;
FORM FORM 1 11 87 14
DW23 2008 34 12 16 3 -
I need to transform the structure of this data:
C S LEN PEN P
C1 S1 10 1 P1
C1 S5 20 2 P2
C2 S2 30 3 P3
C2 S3 40 4 P4
C2 S3 60 6 P5
C3 S4 50 5 P6
C3 S6 70 7 P7
So I could get a a sum of LEN and a count of PEN at every intersection of S and P.
Gracias!CREATE TABLE ORIGINAL
C VARCHAR2(2 BYTE),
S VARCHAR2(2 BYTE),
LEN INTEGER,
PEN INTEGER,
P VARCHAR2(2 BYTE)
INSERT INTO ORIGINAL ( C, S, LEN, PEN, P ) VALUES (
'C1', 'S1', 10, 1, 'P1');
INSERT INTO ORIGINAL ( C, S, LEN, PEN, P ) VALUES (
'C1', 'S5', 20, 2, 'P2');
INSERT INTO ORIGINAL ( C, S, LEN, PEN, P ) VALUES (
'C2', 'S2', 30, 3, 'P3');
INSERT INTO ORIGINAL ( C, S, LEN, PEN, P ) VALUES (
'C2', 'S3', 40, 4, 'P4');
INSERT INTO ORIGINAL ( C, S, LEN, PEN, P ) VALUES (
'C2', 'S3', 60, 6, 'P5');
INSERT INTO ORIGINAL ( C, S, LEN, PEN, P ) VALUES (
'C3', 'S4', 50, 5, 'P6');
INSERT INTO ORIGINAL ( C, S, LEN, PEN, P ) VALUES (
'C3', 'S6', 70, 7, 'P7');
COMMIT; -
Greetings Oracle gurus!
Problem:
I'm trying to write a query that does some data pivoting. I've done this before in the past on smaller data sets, and they've worked great. However, now I'm doing it against a table that has well over a million records. What I'm looking for is the most efficient method in doing this. I've seen ways of doing it by utilizing "union alls" in a WITH query. I've seen ways be creating columns in the query with max() and decode() functions. So... what's the best way to pivot the data? I've seen listagg(), but that comes only with Oracle 11+ I believe... so gotta bust out some sql magic here.
All the good stuff:
Running Oracle 10.2
Sample data:
drop table WO_COMMENTS;
CREATE TABLE "WO_COMMENTS"
"ORDER_NO" varchar2(10),
"COMMENT_SEQ" number,
"COMMENT_TYPE" VARCHAR2(4) ,
"COMMENT_TEXT" VARCHAR2(80)
SET DEFINE OFF;
Insert into WO_COMMENTS (ORDER_NO,COMMENT_SEQ,COMMENT_TYPE,COMMENT_TEXT) values ('00W00284',1,'WOMM','Test1');
Insert into WO_COMMENTS (ORDER_NO,COMMENT_SEQ,COMMENT_TYPE,COMMENT_TEXT) values ('00W00284',2,'WOMM',null);
Insert into WO_COMMENTS (ORDER_NO,COMMENT_SEQ,COMMENT_TYPE,COMMENT_TEXT) values ('00W00284',10,'WOMM','The ');
Insert into WO_COMMENTS (ORDER_NO,COMMENT_SEQ,COMMENT_TYPE,COMMENT_TEXT) values ('00W00284',11,'WOMM','big ');
Insert into WO_COMMENTS (ORDER_NO,COMMENT_SEQ,COMMENT_TYPE,COMMENT_TEXT) values ('00W00284',12,'WOMM','blue ');
Insert into WO_COMMENTS (ORDER_NO,COMMENT_SEQ,COMMENT_TYPE,COMMENT_TEXT) values ('00W00284',13,'WOMM','dog ');
Insert into WO_COMMENTS (ORDER_NO,COMMENT_SEQ,COMMENT_TYPE,COMMENT_TEXT) values ('00W00284',14,'WOMM','died ');
Insert into WO_COMMENTS (ORDER_NO,COMMENT_SEQ,COMMENT_TYPE,COMMENT_TEXT) values ('00W00284',20,'WOMM','Yet ');
Insert into WO_COMMENTS (ORDER_NO,COMMENT_SEQ,COMMENT_TYPE,COMMENT_TEXT) values ('00W00284',21,'WOMM','again');
Insert into WO_COMMENTS (ORDER_NO,COMMENT_SEQ,COMMENT_TYPE,COMMENT_TEXT) values ('00W00284',22,'WOMM',' an ');
Insert into WO_COMMENTS (ORDER_NO,COMMENT_SEQ,COMMENT_TYPE,COMMENT_TEXT) values ('00W00284',23,'WOMM','issue');
Insert into WO_COMMENTS (ORDER_NO,COMMENT_SEQ,COMMENT_TYPE,COMMENT_TEXT) values ('00W00284',24,'WOMM',null);
Insert into WO_COMMENTS (ORDER_NO,COMMENT_SEQ,COMMENT_TYPE,COMMENT_TEXT) values ('00W00284',30,'WOMM','will ');
Insert into WO_COMMENTS (ORDER_NO,COMMENT_SEQ,COMMENT_TYPE,COMMENT_TEXT) values ('00W00284',31,'WOMM','it ');
Insert into WO_COMMENTS (ORDER_NO,COMMENT_SEQ,COMMENT_TYPE,COMMENT_TEXT) values ('00W00284',32,'WOMM','get ');
Insert into WO_COMMENTS (ORDER_NO,COMMENT_SEQ,COMMENT_TYPE,COMMENT_TEXT) values ('00W00284',33,'WOMM','fixed');
Insert into WO_COMMENTS (ORDER_NO,COMMENT_SEQ,COMMENT_TYPE,COMMENT_TEXT) values ('00W00284',34,'WOMM','? ');
Insert into WO_COMMENTS (ORDER_NO,COMMENT_SEQ,COMMENT_TYPE,COMMENT_TEXT) values ('00W00284',35,'WOMM',' ');
Insert into WO_COMMENTS (ORDER_NO,COMMENT_SEQ,COMMENT_TYPE,COMMENT_TEXT) values ('00W00284',36,'WOMM','No ');
Insert into WO_COMMENTS (ORDER_NO,COMMENT_SEQ,COMMENT_TYPE,COMMENT_TEXT) values ('00W00284',37,'WOMM','One ');
Insert into WO_COMMENTS (ORDER_NO,COMMENT_SEQ,COMMENT_TYPE,COMMENT_TEXT) values ('00W00284',38,'WOMM','will ');
Insert into WO_COMMENTS (ORDER_NO,COMMENT_SEQ,COMMENT_TYPE,COMMENT_TEXT) values ('00W00284',39,'WOMM','ever ');
Insert into WO_COMMENTS (ORDER_NO,COMMENT_SEQ,COMMENT_TYPE,COMMENT_TEXT) values ('00W00284',40,'WOMM','know!');
Insert into WO_COMMENTS (ORDER_NO,COMMENT_SEQ,COMMENT_TYPE,COMMENT_TEXT) values ('00W33005',1,'DOCR','Holy ');
Insert into WO_COMMENTS (ORDER_NO,COMMENT_SEQ,COMMENT_TYPE,COMMENT_TEXT) values ('00W33005',2,'DOCR','cow ');
insert into WO_COMMENTS (ORDER_NO,COMMENT_SEQ,COMMENT_TYPE,COMMENT_TEXT) values ('00W33005',3,'DOCR','pie! ');
Insert into WO_COMMENTS (ORDER_NO,COMMENT_SEQ,COMMENT_TYPE,COMMENT_TEXT) values ('00W33005',1,'RTMM','This ');
Insert into WO_COMMENTS (ORDER_NO,COMMENT_SEQ,COMMENT_TYPE,COMMENT_TEXT) values ('00W33005',2,'RTMM','is ');
insert into WO_COMMENTS (ORDER_NO,COMMENT_SEQ,COMMENT_TYPE,COMMENT_TEXT) values ('00W33005',3,'RTMM','an ');
Insert into WO_COMMENTS (ORDER_NO,COMMENT_SEQ,COMMENT_TYPE,COMMENT_TEXT) values ('00W33005',4,'RTMM','& ');
Insert into WO_COMMENTS (ORDER_NO,COMMENT_SEQ,COMMENT_TYPE,COMMENT_TEXT) values ('00W33005',5,'RTMM','!!! ');
insert into WO_COMMENTS (ORDER_NO,COMMENT_SEQ,COMMENT_TYPE,COMMENT_TEXT) values ('00W33005',1,'WOMM','Test9');
commit;
SELECT
ORDER_NO as OBJECT_ID ,
COMMENT_TYPE as ATTACHMENT_REF ,
RTRIM (XMLAGG (xmlelement (E, COMMENT_TEXT || ' ' ) order by comment_seq).extract ('//text()')
, ',') as NOTE
from WO_COMMENTS a
where order_no in ('00W00284', '00W33005')
GROUP BY order_no ,
comment_type ;What I'd like the data to look like:
OBJECT_ID ATTACHMENT_REF NOTE
00W00284 WOMM Test1 The big blue dog died Yet again an issue will it get fixed ? No One will ever know!
00W33005 DOCR Holy cow pie!
00W33005 RTMM This is an & !!!
00W33005 WOMM Test9
With the query used, the '&' in the third record comes across as '&'. How do I deal with special characters in this case?
I know this data has absolutely nothing to do with XML, but using the xmlagg function is sort of a trick I found to do what I need, along with it being very easy to implement. Unsure of how badly this affects performance though. Also note, this is part of a data conversion effort, so it's intended to have some of these columns coming back completely null for the moment. Any "more efficient" methods?
I think I covered everything that folks may need...
Would greatly appreciate any help anyone has to offer :)
Edit: New problem with special characters. New sample data and output supplied.
Edited by: dvsoukup on Aug 16, 2012 11:21 AMHi,
dvsoukup wrote:
Greetings Oracle gurus!
Problem:
I'm trying to write a query that does some data pivoting. To be excruciatingly precise, Pivoting means taking 1 column on N rows, and displaying the information as N columns on 1 row.
Is that what you want, or do you want String Aggregation , where you take 1 column on N rows, and display that as a concatenated list of all N items, in 1 column on 1 row?
I've done this before in the past on smaller data sets, and they've worked great. However, now I'm doing it against a table that has well over a million records. What I'm looking for is the most efficient method in doing this. I've seen ways of doing it by utilizing "union alls" in a WITH query. UNION ALL isn't very efficient (unless you're comparing it to plain UNION), so I'll bet that won't help you. I'm not sure I know the technique you're talking about, though. Just for my curiosity, can you post a link to an example?
I've seen ways be creating columns in the query with max() and decode() functions. That's the standard way to Pivot data in versions earlier than 11.1.
If you really want String Aggregation , however, an alternative to XMLAGG is SYS_CONNECT_BY_PATH. If you don't need the items in any one output row in any particular order, then the user-defined aggregate function STRAGG is very handy. STRAGG can be found at the beginning of the following page, and SYS_CONNECT_BY_PATH is found later on the same page:
http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:2196162600402
My guess is that STRAGG would be the fastest way, but again, STRAGG doesn't guarantee that the output will be
'X / Y / Z'; you're just as likely to get
'X / Z / Y' or
'Z / Y / X' or any of the other permutations.
I'm not sure whether SYS_CONNECT_BY_PATH is faster than XMLAGG, but it's worth trying.
So... what's the best way to pivot the data? I've seen listagg(), but that comes only with Oracle 11+ I believe... so gotta bust out some sql magic here.That's right; LISTAGG is a built-in function for string aggregation, but only in Oracle 11.2 and up.
All the good stuff:
Running Oracle 10.2
Sample data: ...Thanks for posting the sample data and results.
I'm finiding it very difficult to read and understand all of that, however. Could you remove some of the columns, and use shorter strings?
What exactly is the part that you don't understand? I think you're saying that you need to generate a column like the output column called note. I believe you're saying that XMLAGG does what you want, but you'd like to know about other ways that might be more efficient.
Could you post an example that only involves, say, order_no, comm_entry_date and comment_text, with a maximum length of 5 for comment_text? That would be so much easier to me to understtand the problem, and for you to understand the solution. Adapting the solution for all your columns should be very easy.
... I think I covered everything that folks may need... Yes, that's a very thorough message, but it would really help if you could simplify the input data.
Would greatly appreciate any help anyone has to offer :)
Edit: Sorry for causing the display to have a scroll bar go WAY to the right... not sure how to make it more user friendly to be able to see the data n' stuff.I can't think of any way that keeps all the columns and data that you need in your real problem. That's why I'd like you to reduce the problem to something much simpler.
I know you need to have several boilerplate columns, like object_name, in your results, but do they need to be in the problem you post?
I know you need to GROUP BY 4 expressions, but if you see a solution that GROUPs BY 2 of them, you should be able to add the others.
I know your strings can be 80 characters long, but can't you test with strings no longer than 5 characters? -
Dynamic data source in Excel Pivot Table
Hello there,
I am trying to have dynamic data source in pivot table using INDIRECT but getting the error "Reference not valid". Here is how I setup the reference:
Named range: ConsolLink = "'R:\Root\Sub1\Sub2\Consol File.xlsm'!Source_OpexConsol"
"Source_OpexConsol" is defined in the source file as a dynamic name using offset formula.
In the pivot data source, I have tried "=INDIRECT(ConsolLink)" as the data source but that does not work.
I have also tried using INDIRECT in ConsolLink and just referencing "ConsolLink" as the data source. That does not work either.
I am not using Power Pivot. Appreciate it if someone can help.
Thanks.If it is open, then try
Named range: ConsolLink = Range("Consol File.xlsm'!Source_OpexConsol")
And if it is not currently open, then try
Dim W As Workbook
Set W = Workbooks.Open("R:\Root\Sub1\Sub2\Consol
File.xlsm")
Named range: ConsolLink =
Range("Consol File.xlsm'!Source_OpexConsol")
W.Close False -
Can I update datas of Power Query after making relation tables in Power Pivot ?
Can I update datas of Power Query after making relation tables in Power Pivot ?
I want to update datas at day by day to viewing today's graph by Power View on Excel.
Power Query use to transform web site to Power Pivot data model table.
Power Pivot use to making relasing tables, and making measuers.
Regards,
Yoshihiro Kawabata.Hi Yoshihiro,
Can you share an example of the things you are doing in Power Pivot? There are some operations that prevent the query from being refreshed in Power Query; this is not ideal so we are currently working on fixing it.
Thanks for your feedback. -
Power Pivot enable Excel workbook protection with password?
Hi All
We have a power pivot deployment without SharePoint in excel 2013 professional plus. All woks fine until we use a password to protect excel workbook so unauthorised users cannot open it. After enabling password protection we cannot access the power pivot
data model under power pivot excel tab. It tries to upgrade the power pivot model(which is not logical because it didn't do it before and was working fine). thereafter upgrade fails.
Has anyone successfully password protected a power pivot excel 2013 workbook? Is there a workaround to enabling security without SharePoint/office 365 etc?
Thanks
SonnyHi Sonny,
PowerPivot does not support row security or dynamic security. Security for a workbook is just a binary choice – either a user can read a workbook or she can’t.
In this case, I would suggest you consider designing Tabular model which can be secured using row security and dynamic security is also supported. For more information, please see:
Comparing Tabular and Multidimensional Solutions (SSAS):
http://technet.microsoft.com/en-us/library/hh212940.aspx
Regards,
Elvis Long
TechNet Community Support
Maybe you are looking for
-
What is the purpose of the duplicate Local folders (Inbox, Trash, etc.) which are also in the default account?
-
Problem about House Number of Vender Transfer by using LSMW+Batch-Input
Hi, anyone has met the same problem? by using LSMW+Batch-Input method to transfer vender data the field House Number cannot be added. Object: 0040 Vendor Master Method 0002 Shared Program Name RFBIKR00 Program Type B Batch Input Thanks in advance!
-
Authorization object in program
Hi All, I have a requirement to determine the sales areas that a business partner is authorized to edit in my report program. Can this be done by programatically using the Authorization object CRM_BP_SA. Thanks, Shilpi
-
i was reading a tutorial for a little game and when ever i try to run it, i get the error " 1087: Syntax error: extra characters found after end of program. onClipEvent (enterFrame) { " the code is: onClipEvent (enterFrame) { if (Key.isDown(Key.LEFT)
-
Starting coherence server with a ProxyService - How to add multiple members
Hi, I wonder how can we add multiple coherence instacnes to a same cluster when using the ProxyService. I have the following in the configuration file . If we want to start another member to the cluster it fails as the port is already bound. <proxy-s