SSRS Expression for hiding some columns in column group based on parameter
I have a matrix table with column name WeekName which has the values of W1, W2, W3 and W4 which expands 4 columns when run. I need to hide the columns based on a parameter called WeekPar as follows:
If WeekPar = 1, hide columns W1,
If WeekPar = 2, hide columns W1 and W2
What would be the expression for that?
I know how to hide individual columns, but not some of the columns in a group. Is this possible?
Thanks in advance!
Hi QQFA,
After testing the issue in my local environment, we can refer to the steps below to achieve your requirement:
Right-click the WeekName column to open the Column Visibility property dialog box.
Using the expression below to control the Column Visibility (supposing the cell which contains WeekName field named WeekName ):
=switch(Parameters! WeekPar.Value=1,ReportItems! WeekName.Value="W1", Parameters! WeekPar.Value=2,ReportItems! WeekName.Value="W1" or ReportItems! WeekName.Value="W2")
If you have any other questions, please feel free to ask.
Thanks,
Katherine Xiong
Katherine Xiong
TechNet Community Support
Similar Messages
-
Hi All;
I have a field called createdon
Using this field i need to create the SSRS expression for the table as below
Any help much appreciated
Thanks
Pradnya07use expressions as below
assuming this is to be done in SSRS
Today
=COUNT(IIF(
DateDiff(DateInterval.Day,Cdate("01/01/1900"),Fields!createdon.Value) = DateDiff(DateInterval.Day,Cdate("01/01/1900"),Now()),Fields!YourRequiredField.Value,Nothing))
Yesterday
=COUNT(IIF(
DateDiff(DateInterval.Day,Cdate("01/01/1900"),Fields!createdon.Value) = DateDiff(DateInterval.Day,Cdate("01/01/1900"),Now())-1,Fields!YourRequiredField.Value,Nothing))
LastWeek
=COUNT(IIF(
DateDiff(DateInterval.Week,Cdate("01/01/1900"),Fields!createdon.Value) = DateDiff(DateInterval.Week,Cdate("01/01/1900"),Now())-1,Fields!YourRequiredField.Value,Nothing))
Last fortnight
=COUNT(IIF(
(DateDiff(DateInterval.Week,Cdate("01/01/1900"),Fields!createdon.Value) = DateDiff(DateInterval.Week,Cdate("01/01/1900"),Now())-1)
Or (DateDiff(DateInterval.Week,Cdate("01/01/1900"),Fields!createdon.Value) = DateDiff(DateInterval.Week,Cdate("01/01/1900"),Now())-2),Fields!YourRequiredField.Value,Nothing))
Last Month
=COUNT(IIF(DateDiff(DateInterval.Month,Cdate("01/01/1900"),Fields!createdon.Value) = DateDiff(DateInterval.Month,Cdate("01/01/1900"),Now())-1,Fields!YourRequiredField.Value,Nothing))
Year To Date
=COUNT(IIF(DateDiff(DateInterval.Year,Cdate("01/01/1900"),Fields!createdon.Value) = DateDiff(DateInterval.Year,Cdate("01/01/1900"),Now())
And
DateDiff(DateInterval.Day,Cdate("01/01/1900"),Fields!createdon.Value) <= DateDiff(DateInterval.Day,Cdate("01/01/1900"),Now()),Fields!YourRequiredField.Value,Nothing))
Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs -
Hiding some of the columns in Graph in WAD
Hi Friends
In WAD, Ive created a WAD template with a Drop down box ,table and graph all with 1 data provider ( since the char value selected in drop down box has to be effected the data of table and graph) and working fine.
I would like to hide some of the columns in the graph . I ve tried all the properties of the graph but I didnt get.
The columns which I dont want to see in graph are required in the table . So Ive not Hided them in Query (DP of all web items).
Which Property I ve to use to hide some of the columns in graph only.
Plz help me in this
Thanks in advanceHi Sai,
You can go the web item properties (chart) and you can avoid the column in 'Set the sample data' of Texts and Data Selection step(2) of Chart wizard you can check out the 'Category' option to increase of decrease you visibility of the columns.
Also check with the series option in the same wizard.
Hope this will suffice your requirement.
Regards,
Madhu -
SSRS Expression for Conditional Filtering using the "IN" operator
Hello,
I need to filter my dataset based on a parameter:
If Period= 1 then Week must be in (W1, W2, W3), Else Week must be in (W10, W20, W30)
I tried using the "IN" operator but don't know how to create the expression for the "Value" field. I tried the following:
iif(Parameters!Period.Value = 1,
"W1, W2, W3",
"W10, W20, W30")
But it doesn't work.
Expression: Week
Operator: IN
Value: ???
Any help would be highly appreciated!Hi,
Use split function.
See this expression: IIF(Parameters!Period.Value = 1, SPLIT("W1,W2,W3",","), SPLIT("W10,W20,W30",","))
http://social.msdn.microsoft.com/Forums/sqlserver/en-US/8da78c9b-7f0c-42f1-a9c4-82f065f317c9/using-the-in-operator-in-ssrs-expressions
Thanks Shiven:) If Answer is Helpful, Please Vote -
Hi All,
Below is the my table with SSRS expressions marked as A and B
Expression A gets the serial number 1, 2, 3 etc
I need to get expression A/B
Any help on this much appreciated
Thanks
Pradnya07It's look like you want B/A, not A/B.
You can try couple things. If you are allowed to use ReportItems and refer to the textbox value, then simply use this:
=ReportItems!textboxnameforB.Value / ReportItems!textboxnameforA.Value
If that gives you error as far as not allow to use ReportItems, then try create a divide function in custom code and then pass the value to it.
Public Function Divide(Num1 as double, Num2 as double) AS double
IF IsNothing(Num1) Or IsNothing(Num2) Or Num1 = 0 Or Num2 = 0 Then
Divide = 0
ELSE
Divide = Num1 / Num2
END IF
End Function
Then, simply use this in the textbox you want the value:
=code.Divide(RunningValue(Fields!new_programmeoutputid.Value,CoutDistinct, "new_outputs"),RunningValue(Fields!new_claimmonthid.Value,CountDistinct,
Nothing))
If that still does not work, then try to bring these values in the query itself.
good luck. -
SSRS expression for grouping minutes
Hi All,
Can you please help me to write an SSRS expression to group minutes
=SWITCH(
Fields!TotalHours.Value = 0
and 240,
"0 To 4 hrs",
Fields!TotalHours.Value = 241
and480,
"5 To 8 hrs",
Fields!TotalHours.Value = 481
and720,
"9 To 12 hrs",
Fields!TotalHours.Value = 721
and960 ,
"13 To 16 hrs",
Fields!TotalHours.Value = 961
and1200,
"17 To 20 hrs",
Fields!TotalHours.Value = 1201
and12000000,
"More than 20 hrs"
Any help much appreciated
Thanks
Pradnya07Try this...
= SWITCH ( Fields!TotalHours.Value <= 240, "0 to 4 Hrs",
Fields!TotalHours.Value <= 480, "5 to 8 Hrs",
Fields!TotalHours.Value <= 720, "9 to 12 Hrs",
Fields!TotalHours.Value <= 960, "13 to 16 Hrs",
Fields!TotalHours.Value <= 1200, "17 to 20 Hrs",
Fields!TotalHours.Value > 1200, "More than 20 Hrs") -
SSRS expression for difference between two currency values
Hi All;
I need to get the difference between two currency values
Below is my report
I need to get differene between Actual Income and Profile Income and this value should be in "£" In this example it should be £0.00
Any help much appreciated
Thanks
Pradnya07=sum(Fields!ProfileIncome.Value - Fields!ActualIncome.Value)
This could have either field first, but depends on which field is expected to be larger. You would then format the textbox to show in pounds.
HTH -
Hello, Expert,
Could you please help me with the following problem? Thanks in advance!
I have designed the matrix report (SSRS 2012) with database table structure looks like below.
Week
Version
Count
Week1
V1.1
4000
Week1
V1.2
4000
Week1
V1.3
4000
Week2
V1.1
3000
Week2
V1.2
3000
Week2
V1.3
3000
Week3
V1.1
2000
Week3
V1.2
2000
Week3
V1.3
2000
Week4
V1.1
1000
Week4
V1.2
1000
Week4
V1.3
1000
The matrix report displays like below. Column grows based on no of Week in the table.
Week1
Week2
Week3
Week4
V1.1
4000
3000
2000
1000
V1.2
4000
3000
2000
1000
V1.3
4000
3000
2000
1000
What I want to do now is: instead of the Count values, I need to calculate the percentage of each week over the
Count in Week1 so that each cell displays Count(Week2)/Count(Week1), Count(Week3)/Count(Week1), etc. What is the SSRS expression for that? I’m new to SSRS, Please help!Heidi,
Thank you so much for your reply and solution! Now I know how to get the first field in a group. But I can't apply your solution directly just yet because in order to explain my problem I simplified my data structure. My real data structure has a nested
group like this:
Week VersionMajor VersionMinor Count
Week1 V1 V1.1 2000
Week2 V1 V1.1 1500
Week3 V1 V1.1 800
Week1 V1 V1.2 1000
Week2 V1 V1.2 500
Week3 V1 V1.2 200
Week1 V1 V1.1 2000
Week2 V1 V1.1 1500
Week3 V1 V1.1 800
Week1 V1 V1.2 1000
Week2 V1 V1.2 500
Week3 V1 V1.2 200
Here is the query for the above data:
SELECT 'Week1' AS Week, 'V1' AS VersionMajor, 'V1.1' AS VersionMinor, 2000 AS Count
UNION ALL
SELECT 'Week2' AS Week, 'V1' AS VersionMajor, 'V1.1' AS VersionMinor, 1500 AS Count
UNION ALL
SELECT 'Week3' AS Week, 'V1' AS VersionMajor, 'V1.1' AS VersionMinor, 800 AS Count
UNION ALL
SELECT 'Week1' AS Week, 'V1' AS VersionMajor, 'V1.2' AS VersionMinor, 1000 AS Count
UNION ALL
SELECT 'Week2' AS Week, 'V1' AS VersionMajor, 'V1.2' AS VersionMinor, 500 AS Count
UNION ALL
SELECT 'Week3' AS Week, 'V1' AS VersionMajor, 'V1.2' AS VersionMinor, 200 AS Count
UNION ALL
SELECT 'Week1' AS Week, 'V1' AS VersionMajor, 'V1.1' AS VersionMinor, 2000 AS Count
UNION ALL
SELECT 'Week2' AS Week, 'V1' AS VersionMajor, 'V1.1' AS VersionMinor, 1500 AS Count
UNION ALL
SELECT 'Week3' AS Week, 'V1' AS VersionMajor, 'V1.1' AS VersionMinor, 800 AS Count
UNION ALL
SELECT 'Week1' AS Week, 'V1' AS VersionMajor, 'V1.2' AS VersionMinor, 1000 AS Count
UNION ALL
SELECT 'Week2' AS Week, 'V1' AS VersionMajor, 'V1.2' AS VersionMinor, 500 AS Count
UNION ALL
SELECT 'Week3' AS Week, 'V1' AS VersionMajor, 'V1.2' AS VersionMinor, 200 AS Count
And my matrix table looks like this:
What I need to do is to calculate the percentage of each week over week1 for
1) V1 Total
2) V1.1
3) V1.2
I can't use your solution directly because I need to apply Sum function for each cell and the Sum function gives me error when I try to use it on the denominator
First(Fields!Count.Value,"VersionMinor"). If you could help me further to get to the final solution, I'd really appreciate it!!
Happy New Year! -
SSRS - Expression to color column value dynamically in Matrix
Hi ,
I have a matrix which looks like :
The <<Expr>> value can be 1 /0 /"-" .
The Expr value is being calculated dynamically.
The data set query I am using has a column called due_days.
In the color expression of the <<Exp>> box I am using the expression as :
=IIf(Fields!Due_Days.Value>14 and Fields!Notes_Count.Value>0,"Blue",(Iif(Sum(Fields!Notes_Count.Value)=0 ,"Red","Black")))
My requirement is if the Due_Days column value is >14 then I need to highlight the value as blue else black and if value is 0 then red. When I use the above query it is just highlighting the color blue for 1st column only. Eg: 4th row . Due days for month
of Oct and Nov is > 14 but it shows blue only for month of oct.
How can i resolve the issue?In select query i have 5 columns:
Due days(Which is difference between 2 dates) ,
Notes count (Which is just a count of notes entered or not having value 0/1 and value '-' if another column CRD is greater than the matrix month and year.)Eg: below date 11/12/2014 is greater than Oct 2014 hence Oct 2014 should have "-"
Month Name , Year , Month Nbr (last 6 months which I cross joined with the table to get counts for each month)
The matrix has year and last 6 month as column groups
Color coding should be if notes count is 0 then red ,if notes count is 1 and due_days> 14 then blue else black . When i try to use expression for color as i mentioned above, it colors only 1st colum.eg: 2nd row
Nov 2014 is blue but for jan 2014 also it should show blue as due days>14 .
Is there any way i can do that ??
Eg: data set returns value as :
Due Days CRD Month
Month_Nbr Year Notes _Count
5 2014-11-28 00:00:00.000 December 12 2014
0
5 2014-11-28 00:00:00.000 February 2 2015
0
5 2014-11-28 00:00:00.000 January 1 2015
0
5 2014-11-28 00:00:00.000 November 11 2014 1
5 2014-11-28 00:00:00.000 October 10 2014 0
5 2014-11-28 00:00:00.000 September 9 2014 0
Matrix is of the form :
YEAR
MONTH
CRD Notes_count -
EL expression for maximum length of column of underlying EO
Hi all,
I am using ADF Faces with ADF BC as the model layer. I have a simple inputText component on the screen that shows 32 characters (columns property = 32). The underlying database table can hold 128 characters. Is there any EL expression that I can use for the maximum length? I have tried the EL expression builder, but I don't see any property that looks promising (#{bindings.fieldname.<something>} is what I'm looking for)
Thanks,
JohnChris,
In 10.1.3.2, we already automatically drop an EL expression for the Columns property that is bound to the Display Width hint.
It will look like:
<af:inputText value="#{bindings.Dname.inputValue}"
label="#{bindings.Dname.label}"
required="#{bindings.Dname.mandatory}"
columns="#{bindings.Dname.displayWidth}">
<af:validator binding="#{bindings.Dname.validator}"/>
</af:inputText>If the developer has not supplied a custom value of Display Width, then it defaults to the maximum length of the attribute.
If you have provided a custom Display Width hint that is shorter than the maximum length, then you can reference the maximum length by using the precision property of the attribute definition, as shown in the EL expression for maximumLength below.
<af:inputText value="#{bindings.Dname.inputValue}"
label="#{bindings.Dname.label}"
required="#{bindings.Dname.mandatory}"
columns="#{bindings.Dname.displayWidth}"
maximumLength="#{bindings.Dname.attributeDef.precision}">
<af:validator binding="#{bindings.Dname.validator}"/>
</af:inputText> -
Show different key fields for different caracteristics in the column.
Hi, experts
I am creating a query where there are 4 colomns reprensenting 4 different dates. But I would like to display diffferent key fields for them. For example, under DAY 1, i would like to diplay KeyField 1, for DAY2, DAY3 and DAY4, KeyField 2 et 3 will be added under them.
To do that, i made these key fields "Constant selection" and made some definition in the cells-------
On the line of DAY1 in the colomn KeyField 2 and KeyField 3, I made them "Always Hide".
But I didn't get what i wanted as the two columns (KF2 et KF3) still appear in the report, even if there are no data in these two columns.
Is it possible to realise this requirement:
DAY1 DAY2 DAY3
KF1 KF2 KF3 KF2 KF3
Thanks in advance!!!!There is no need to define a cell for this, use a restricted key figure:
KF1 needs to be restricted by Day1
KF2 restrict it by Day2 and so on,
and use those restricted figure in the key figure section, but to make the column more descriptive use a text variable for the name of the columns.
this should be easier than cell definition.
thanks.
Wond -
SSRS Matrix report to show or hide year column based on parameter value "Date" selected.
Hey experts!
I have a requirement an ssrs matrix report should display columns (year/s) based on parameter value (date/s).
My Dataset fileds are: Product, Year_name, Month_name, Date
Currently my report output looks like this-
Param Date: 2013-08-01 00:00:0.000
Product +Calender2011 +Calender2012 -Calender 2013........ +Calender2014
Total
Total Jan13 Feb 13 Mar13.. Dec13 Total Total
Abc 100
220
10 20 30....... 20 250 400
Xyz 110
200 50 80 40....... 30 450 600
My requirement: if I'm selecting Date parameter value as '2013-xx-xx' I should only able to see Year column 'Calender2013' and rest of the years should hide. Similarly If I'm selecting Date parameter value as '2014-xx-xx' I should only able to
see Year column 'Calender2014' .
Appreciate your kindly help.
AfanHi Afan,
According to your description, you want to only show the selected year on your report, right?
In this case, you need to get the year from the date parameter using the expression below
=Year(Parameters!Date.Value)
And then use the expression below to get the year from Year_Name field.
=Right(Fields!Year_Name.Value,4)
Then add a filter to the dataset to filter the data like below
Expression:=Year(Parameters!Date.Value)
Operator:=
Value:=Right(Fields!Year_Name.Value,4)
Reference
http://msdn.microsoft.com/en-IN/library/dd255287.aspx
If you have any questions, please feel free to ask.
Regards,
Charlie Liao
TechNet Community Support -
SQL Data Sync - column type invalid for use as a key column
Hello,
our sync group is failing to do the sync. Here's a tracingID:
For more information, provide tracing ID ‘e3e568b5-140a-4ae5-a4c8-c178c6bf805d’ to customer support.
I must say, that the column in DB is not a PK or INDEX-ed, it was initially VARCHAR(MAX), after some reading I changed it to VARCHAR(200) and later to TEXT, but the result of syncing is still the same.
Thank you,
BojanHi Bojan,
The error “column type invalid for use as a key column” could be due to the existence of unsupported data types or column properties when implementing the synchronization. I recommend you check your database according to this article:
SQL Database Data Types supported by SQL Data Sync.
Besides, before you design and implement a data synchronization plan, please check the following articles about system requirements for SQL Data Sync and so on.
System Requirements for SQL Data Sync
https://msdn.microsoft.com/en-us/library/azure/jj127278.aspx
Known SQL Data Sync Limits
https://msdn.microsoft.com/en-us/library/azure/jj590380.aspx
SQL Data Sync Best Practices
https://msdn.microsoft.com/en-us/library/azure/hh667328.aspx
Thanks,
Lydia Zhang
Lydia Zhang
TechNet Community Support -
How to get count of unique values of column B for each unique value of column A in Excel 2010?
I have an excel sheet containing 72,000 rows in Excel 2010, column A is "site name", column B is category. I want a result that shows number of sites for each category.
Column A Column B
site 1 Category 1
Site 1 Category 1
Site 2 Category 1
site 3 Category 2
site 3 Category 2
site 4 Category 2
site 5 Category 2
I want this result:
Category 1 2
Category 2 3
I tried some formula in a 3rd column and created a pivot table on that column, but it did not give me the result i want.
Any one has an idea ? what is the easiest way to achieve this?
Appreciate any pointerI tried both formula referenced in these two post (I think they are a little simpler than the one above):
http://stackoverflow.com/questions/11876238/simple-pivot-table-to-count-unique-values
http://stackoverflow.com/questions/18898138/pivot-table-count-unique-values-excel-2010
They both worked! and I got the result for my 72,000 rows!
Thanks for your help! -
Help for a query to add columns
Hi,
I need for a query where I should add each TableC value as an additional column.
Please suggest...
I have 3 tables (TableA, TableB, TableC). TableB stores TableA Id and TableC stores TableB Id
Considering Id of TableA.
Sample data
TableA :
ID NAME TABLENAME ETYPE
23 Name1 TABLE NAMEA Etype A
TableB :
ID A_ID RTYPE RNAME
26 23 RTYPEA RNAMEA
61 23 RTYPEB RNAMEB
TableC :
ID B_ID COMPNAME CONC
83 26 Comp Name AA 1.5
46 26 Comp Name BB 2.2
101 61 Comp Name CC 4.2
Scenario 1: AS PER ABOVE SAMPLE DATA Put each TableC value as an additional column.
For an Id in TableA(23) where TableB contains 2 records of A_ID (26, 61) and TableC contains 2 records for 26 and 1 record for 61.
Output required: Put each TABLEC value as an additional column
TableA.NAME TableA.ETYPE TableB.RTYPE TableC_1_COMPNAME TableC_1_CONC TableC_2_COMPNAME TableC_2_CONC
Name1 EtypeA RTypeA Comp Name AA 1.5 Comp Name BB 2.2 so on..
Name1 EtypeA RTypeB Comp Name CC 4.2 NULL NULL
Scenario 2: If Table C contains ONLY 1 row for each Id in TableB, output should be somewhat
Output:
TableA.NAME TableA.ETYPE TableB.RTYPE TableC_1_COMPNAME
TableC_1_CONCvalue value value value valueHi,
Welcome to the forum!
Do you want the data from TableC presented
(1) in one column, or
(2) in several columns (a different column of results for each row in the original TableC)?
(1) Is called String Aggregation and is easier than (2).
The best way to do this is with a user-defined aggregate function (STRAGG) which you can copy from asktom.
Ignoring TableA for now, you could get what you want by saying
SELECT b.rtype
, STRAGG ( c.compname
|| ' '
|| c.conc
) AS c_data
FROM TableB b
JOIN TableC c ON b.id = c.b_id
GROUP BY b.rtype;(2) Presenting N rows of TableC as it they were N columns of the same row is called a pivot. Search for "pivot" or "rows to columns" to find examples of how to do this.
The number of columns in a result set is hard-coded into the query. If you don't know ahead of time how many rows in TableC will match a row in TableB, you can:
(a) guess high (for example, hard-code 20 columns and let the ones that never contain a match be NULL) or,
(b) use Dynamic SQL to write a query for you, which has exactly as many columns as you need.
The two scripts below contain basic information on pivots.
This first script is similar to what you would do for case (a):
-- How to Pivot a Result Set (Display Rows as Columns)
-- For Oracle 10, and earlier
-- Actually, this works in any version of Oracle, but the
-- "SELECT ... PIVOT" feature introduced in Oracle 11
-- is better. (See Query 2, below.)
-- This example uses the scott.emp table.
-- Given a query that produces three rows for every department,
-- how can we show the same data in a query that has one row
-- per department, and three separate columns?
-- For example, the query below counts the number of employess
-- in each departent that have one of three given jobs:
PROMPT ========== 0. Simple COUNT ... GROUP BY ==========
SELECT deptno
, job
, COUNT (*) AS cnt
FROM scott.emp
WHERE job IN ('ANALYST', 'CLERK', 'MANAGER')
GROUP BY deptno
, job;
Output:
DEPTNO JOB CNT
20 CLERK 2
20 MANAGER 1
30 CLERK 1
30 MANAGER 1
10 CLERK 1
10 MANAGER 1
20 ANALYST 2
PROMPT ========== 1. Pivot ==========
SELECT deptno
, COUNT (CASE WHEN job = 'ANALYST' THEN 1 END) AS analyst_cnt
, COUNT (CASE WHEN job = 'CLERK' THEN 1 END) AS clerk_cnt
, COUNT (CASE WHEN job = 'MANAGER' THEN 1 END) AS manager_cnt
FROM scott.emp
WHERE job IN ('ANALYST', 'CLERK', 'MANAGER')
GROUP BY deptno;
-- Output:
DEPTNO ANALYST_CNT CLERK_CNT MANAGER_CNT
30 0 1 1
20 2 2 1
10 0 1 1
-- Explanation
(1) Decide what you want the output to look like.
(E.g. "I want a row for each department,
and columns for deptno, analyst_cnt, clerk_cnt and manager_cnt)
(2) Get a result set where every row identifies which row
and which column of the output will be affected.
In the example above, deptno identifies the row, and
job identifies the column.
Both deptno and job happened to be in the original table.
That is not always the case; sometimes you have to
compute new columns based on the original data.
(3) Use aggregate functions and CASE (or DECODE) to produce
the pivoted columns.
The CASE statement will pick
only the rows of raw data that belong in the column.
If each cell in the output corresponds to (at most)
one row of input, then you can use MIN or MAX as the
aggregate function.
If many rows of input can be reflected in a single cell
of output, then use SUM, COUNT, AVG, STRAGG, or some other
aggregate function.
GROUP BY the column that identifies rows.
PROMPT ========== 2. Oracle 11 PIVOT ==========
WITH e AS
( -- Begin sub-query e to SELECT columns for PIVOT
SELECT deptno
, job
FROM scott.emp
) -- End sub-query e to SELECT columns for PIVOT
SELECT *
FROM e
PIVOT ( COUNT (*)
FOR job IN ( 'ANALYST' AS analyst
, 'CLERK' AS clerk
, 'MANAGER' AS manager
NOTES ON ORACLE 11 PIVOT:
(1) You must use a sub-query to select the raw columns.
An in-line view (not shown) is an example of a sub-query.
(2) GROUP BY is implied for all columns not in the PIVOT clause.
(3) Column aliases are optional.
If "AS analyst" is omitted above, the column will be called 'ANALYST' (single-quotes included).
{code}
The second script, below, shows one way of doing a dynamic pivot in SQL*Plus:
{code}
How to Pivot a Table with a Dynamic Number of Columns
This works in any version of Oracle
The "SELECT ... PIVOT" feature introduced in Oracle 11
is much better for producing XML output.
Say you want to make a cross-tab output of
the scott.emp table.
Each row will represent a department.
There will be a separate column for each job.
Each cell will contain the number of employees in
a specific department having a specific job.
The exact same solution must work with any number
of departments and columns.
(Within reason: there's no guarantee this will work if you
want 2000 columns.)
Case 0 "Basic Pivot" shows how you might hard-code three
job types, which is exactly what you DON'T want to do.
Case 1 "Dynamic Pivot" shows how get the right results
dynamically, using SQL*Plus.
(This can be easily adapted to PL/SQL or other tools.)
PROMPT ========== 0. Basic Pivot ==========
SELECT deptno
, COUNT (CASE WHEN job = 'ANALYST' THEN 1 END) AS analyst_cnt
, COUNT (CASE WHEN job = 'CLERK' THEN 1 END) AS clerk_cnt
, COUNT (CASE WHEN job = 'MANAGER' THEN 1 END) AS manager_cnt
FROM scott.emp
WHERE job IN ('ANALYST', 'CLERK', 'MANAGER')
GROUP BY deptno
ORDER BY deptno
PROMPT ========== 1. Dynamic Pivot ==========
-- ***** Start of dynamic_pivot.sql *****
-- Suppress SQL*Plus features that interfere with raw output
SET FEEDBACK OFF
SET PAGESIZE 0
SPOOL p:\sql\cookbook\dynamic_pivot_subscript.sql
SELECT DISTINCT
', COUNT (CASE WHEN job = '''
|| job
|| ''' ' AS txt1
, 'THEN 1 END) AS '
|| job
|| '_CNT' AS txt2
FROM scott.emp
ORDER BY txt1;
SPOOL OFF
-- Restore SQL*Plus features suppressed earlier
SET FEEDBACK ON
SET PAGESIZE 50
SPOOL p:\sql\cookbook\dynamic_pivot.lst
SELECT deptno
@@dynamic_pivot_subscript
FROM scott.emp
GROUP BY deptno
ORDER BY deptno
SPOOL OFF
-- ***** End of dynamic_pivot.sql *****
EXPLANATION:
The basic pivot assumes you know the number of distinct jobs,
and the name of each one. If you do, then writing a pivot query
is simply a matter of writing the correct number of ", COUNT ... AS ..."\
lines, with the name entered in two places on each one. That is easily
done by a preliminary query, which uses SPOOL to write a sub-script
(called dynamic_pivot_subscript.sql in this example).
The main script invokes this sub-script at the proper point.
In practice, .SQL scripts usually contain one or more complete
statements, but there's nothing that says they have to.
This one contains just a fragment from the middle of a SELECT statement.
Before creating the sub-script, turn off SQL*Plus features that are
designed to help humans read the output (such as headings and
feedback messages like "7 rows selected.", since we do not want these
to appear in the sub-script.
Turn these features on again before running the main query.
{code}
Maybe you are looking for
-
Please help, this is urgent
Hi I have created a grid using JSP and HTML which has three columns and multiple rows. The cells are actually the text boxes and their names are EmpNo, Value1, and value2. And every row's column's control name is same. They display like this EmpNo Va
-
How can I use New iPad in Japan?
I just bought the new iPad and was planning to use it to access the internet on my upcoming trip to Japan. When I purchased the device last week, the Mac Genius assured me that all I needed to do was buy a SIM card once I got there. Unfortunately, as
-
I have the microsoft arc mouse and keyboard and each of them have seperate transrecievers. The macbook air only has two ports. If I bought a usb hub would this enable me to plug the transrecievers into the hub so I would have 1 usb port free? Or is t
-
Re-installing an in-app purchase from lite to full version
Hi, I know that if I delete a purchased app by accident I can redownload from the app store and it will recognize I had previously purchased the app and install again without charging. What about an app that the full version was purchased from within
-
Items in trash, but icon is "empty"
I've seen discussions on trash issues, but not quite this particular problem. I have items in the trash, but the trash icon remains empty instead of full, and "empty trash" is greyed out. It isn't just a particular file/files - it happens with anythi