SQL for combine the column
Hi there are two records, as follows
a L1 M1
a L1 M2
the result expected
a L1 M1,M2
Could you help to give an example SQL for the result. Thanks for your help!
Edited by: user12984790 on Jul 2, 2012 12:55 AM
user12984790 wrote:
11gThat is a product name. Not a product version. The version is a 4 digit number, e.g. 11.1.0.0 or 11.2.0.2. And there are differences in behaviour between versions.
As for your problem - it is a FAQ (frequently asked question). Please read the very 1st posting to this forum - the forum FAQ. Pivots are covered in detail.
Similar Messages
-
Help needed in PL/SQL for updating the column for multiple records
Hi,
I am new to PL/SQL and need some help. What is the most effiecient way to update some field in a table as I may need to update thousands of records. I have a coulmn groupid can have multiple records tied to it. All the records attached to some groupid have a priority field also.
How can I update the prorityfield value for all the groupids in a profiecient way. Here is a sample data
GroupId Priority
1 1
1 2
1 3
1 4
1 5
2 1
2 2
2 3
3 1Here I have three groups 1, 2, 3. Now if any group contains only one record the priority remains same e.g. groupid=3 on top. If any group contains more than one record e.g. groupid=1 & 2 I want to re-arrange the priority fields e.g. If I want to update groupid=1 now if I change the priority of 2 to 5 (make it the last) I want to rearrange the remaing records priority i.e. if 2 becomes 5 as I have 5 rows for groupid=1 then 5 becomes 4, 4 becomes 3, 3 becomes 2 and 1 remains the same.
Same wya if I want to make the priority 1 to 3 for groupid=2 then need 2 to become 1 and 3 to become 2 etc....
Any help is appreciated.
ThanksHi,
You don't need PL/SQL to do this (though you can put the following in PL/SQL if you want to):
UPDATE table_x
SET priority = CASE
WHEN groupid = 1
AND priority = 2
THEN 5
WHEN groupod = 1
AND priority BETWEEN 3 AND 5
THEN priority - 1
WHEN groupid = 2
THEN
CASE
WHEN prioity = 1
THEN 3
ELSE priority - 1
END
END
WHERE groupId IN (1, 2)
AND ( priority BETWEEN 2 AND 5
OR groupid = 2
);There are lots of different techniques that can reduce your coidng: for example, the nested CASE statement used for groupid=2 above.
You could do several smaller UPDATEs (for example, one just for groupid=1). Execution will be slower, but coding and testing will be faster.
You could make the "magic numbers" 2 (for groupid=1) and 1 (for groupid=2) variables, even outside of PL/SQL.
If you need more help, post the information that Satyaki requested. -
Function returning SQL - dynamically select the column
Hi there,
[Oracle 11g],
Hi there,
I want to dynamically select the column to be displayed.
Or lets say it in an easier way regarding the EMP Table:
I got a table called teststable with value1 and value2 in it.
Value1 is EMPNO
Value 2 is DEPTNO
Now I like to have something like this:
Select (Select Value1 from testtable),(Select Value2 from testtable) from EMP This will not work. So I need a function for this. Does someone now how to get this to work? Thx in advance. Thorsten+ 1 to the above replies.
An example to pick the column name dynamically from a table and rendering the output of EMP table as a XMLTYPE is here.Pushing it a little bit further, you can project back XML as relational rows and columns :
SQL> with testtable (value1, value2) as (
2 select 'EMPNO', 'DEPTNO' from dual
3 )
4 select x.*
5 from testtable t
6 , xmltable(
7 'for $r in fn:collection("oradb:/SCOTT/EMP")/ROW
8 return element r {
9 $r/*[local-name()=$v1]
10 , $r/*[local-name()=$v2]
11 }'
12 passing t.value1 as "v1"
13 , t.value2 as "v2"
14 columns value1 varchar2(30) path '*[1]'
15 , value2 varchar2(30) path '*[2]'
16 ) x
17 ;
VALUE1 VALUE2
7369 20
7499 30
7521 30
7566 20
7654 30
7698 30
7782 10
7839 10
7844 30
7900 30
7902 20
7934 10
12 rows selected -
Program (PL/SQL) for count the registers of all tables in a schema
Hi...
I create a little program , for count the registers of all tables in the schema...
If you need , send me your email...
Atte
HectorHi,
You can create a script by yourself by executing the script mentioned below:
Connect as sys or system....
SQL> spool test.sql
SQL> select 'select count(*) from '||owner||'.'||table_name||';' from dba_tables;
SQL> spool off;
Hope this helps.
Regards,
-Praveen.
http://myracle.wordpress.com -
How to Export VO query data for all the columns.
Hi All,
I have advanced Table where i will be displaying only few of the columns from the VO query, when i export it will display only those columns which are displayed in advanced Table, so is it possible to export other columns also?
Thanks
BabuI faced this similar issue ...as per my knowledge if the widget for the underlying VO attribute is rendered then only one can export the data...a possible workaround is..u can create a similar page showing the respective columns intended to be exported and redirect to tht page and export it from there .....
-
T-SQL for finding the unused tables which are consuming maximum disk space.
Hi,
Need help in writing a T-SQL that can return me the unused or least used tables in a database and are consuming a lot of disk space.
ThanksRefer
http://gallery.technet.microsoft.com/SQL-List-All-Tables-Space-baf0bbf9
create table #TableSize (
Name varchar(255),
[rows] int,
reserved varchar(255),
data varchar(255),
index_size varchar(255),
unused varchar(255))
create table #ConvertedSizes (
Name varchar(255),
[rows] int,
reservedKb int,
dataKb int,
reservedIndexSize int,
reservedUnused int)
EXEC sp_MSforeachtable @command1="insert into #TableSize
EXEC sp_spaceused '?'"
insert into #ConvertedSizes (Name, [rows], reservedKb, dataKb, reservedIndexSize, reservedUnused)
select name, [rows],
SUBSTRING(reserved, 0, LEN(reserved)-2),
SUBSTRING(data, 0, LEN(data)-2),
SUBSTRING(index_size, 0, LEN(index_size)-2),
SUBSTRING(unused, 0, LEN(unused)-2)
from #TableSize
select * from #ConvertedSizes
order by reservedKb desc
drop table #TableSize
drop table #ConvertedSizes
--Prashanth -
How to Include Double Quotes in the Column Name
Hi,
I am using Dynamic Sql for creating the columns of a table. I am getting a situation where the user will give the double quotes for some column names. So,Can we add double quote to the column name.
Thanks in advance.
Regards,
Alok Dubeyhttp://download.oracle.com/docs/cd/B28359_01/server.111/b28286/sql_elements008.htm
However, neither quoted nor nonquoted identifiers can contain double quotation marks or the null character -
Design Table with no of columns used for calculating the total
Hello,
I need to design a table/s for calculating the column values based on the operators provided. Like I have a table say
TableID, Col1 , Col2 ,Col3 ... Total Value
Total Value Column is calculating Col1 (operator value provided by the user) Col 2 (operator value provided by the user) Col3 etc
Although I m thinking to create another table which stores operator values, however not sure how to calculate the total.
like it can be COl 1 +Col2 -Col3 %Col4 etc.
Please help.Can you show some data example+ desired result?
DECLARE @t TABLE(a INT,b INT,c INT);
INSERT @t VALUES(1,2,3),(9,8,7),(4,6,5);
SELECT *
, ( SELECT COUNT(val)
FROM (VALUES (a)
, (b)
, (c)
) AS value(val)
) AS CountVal
FROM @t;
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 -
Oracle 10g - Defining the column name in Non English
Hi Experts,
I have an exisitng application which is developed on Windows using ASP Technology and uses Oracle 10g 10.1.0.2.0.
The application is supported with an instance of Data Base within which multiple tablespaces are created for different clients. The application is developed in such a way that some of the tables arecreated dynamically and the columns are named using the data entered through the UI.
This application needs to be globalized now. The problem is, the column name entered through the UI can be in any language based on the client's settings and those values in turn will be used for naming the columns in the tables.
1) Can I have the column names to be named using non english characters in Oracle 10g DB? If so,
1.1) what should I do to configure the exisiting Oracle instance to support it?
1.2) To what level is that configuration possible, is it per DB instance level (or) can it be done at Tablespace level. I would like to configure each tablespace to host tables with columns defined with different languages, say for example, tablespace 1 will have tables with Japaenese column names and tablespace 2 will have tables with German column names?
2) What should I do to make my entire DB to support unicode data i.e., to accept any language strings. Currently all strings are declared as VarChar2, should I change all VarChar2 to NVarChar2 (or) is there a way to retain the VarChar2 as is and make some database wide setting?
Please note that I do not have an option of retaining the column in English as per the Business Requirement.
Envionment:
OS - Windows 2003 32 bit
Oracle 10g 10.1.0.2.0
UI forms in ASP
TIA,
Prem1. Yes, you can.
SQL> create table ÜÝÞ( ßàá number(10));
Table created.
SQL> insert into ÜÝÞ values (10);
1 row created.1.1 and 1.2 and 2. You can choose UTF as your default character set. It allows the user of non-English characters in VARCHAR columns in your whole database. It is not per tablespace.
SQL> create table ÜÝÞ( ßàá varchar2(100));
Table created.
SQL> insert into ÜÝÞ values ('âãäçìé');
1 row created. -
Hi,
I'm trying to use LINQ to SQL with a top down approch using my own POCO classes. I'm using a XML file for the external mapping but in order to avoid typing a long file by hand I found that I could use the O/R designer to create the .dbml and from there I
could use SqlMetal.exe to generate the map file from the .dbml. The only thing is that, by default, SqlMetal generates a map file which includes the 'storage' attribute for all the columns of the database. For example:
<
Column
Name="Ticker"
Member="Ticker"
Storage="_Ticker"
DbType="NChar(20)
NOT NULL"
CanBeNull="false"
/>
However, in my code I only use automatic properties (Ticker, in this example) and not properties with the corresponding private field. Basically, I don't have any field "_Ticker" in my class. I found out that this the reason why I'm getting the error
"Bad Storage property: '_Ticker' on member 'TTS.Domain.Asset.Ticker" when trying to add an entity to the database. However, ff I delete the all the 'storage' attributes from my mapping file everything works fine.
Is there a way so I could use SqlMetal to generate a map file from a .dbml file but in which it never includes the 'storage' attribute?
Thanks.
Best,
Miguel T.
This is reason why I'm getting the error.Hi Serguey,
I was expecting that answer but I still had some hope that it could be possible! I checked those 2 links before sending my question.
Currently, I'm deleting the storage attributes everytime that I generate a mapping file. The issue is that I will have to do this eveytime that I need to add data in my O/R designer which happens quite frequently since I'm working with iterations in my project.
It's not very practical but it's still better than write the additional data by hand.
I don't know how I could create my own mapping validation in order to exclude the 'storage' attributes everytime that I generate a mapping file from a .dbml file with SqlMetal but I will check that option too.
Thanks for your helps.
Best,
Miguel. -
Return only the columns with different values.
Hi all,
I am trying to solve a seemingly trivial problem but can't seem to get any straight answer anywhere in any forum. Consider a single table with 5 columns and only two rows:
row_id first_name last_name age gender
1 John doe 27 M
1 Jane doe 27 F Assume there is no primary key or any other constraint. Also assume that there are only and only two rows in this table. So I basically need a query that, in the above set of rows, would return first_name and gender, as they are the only differing columns in the two rows, and also their values. Even if i can somehow get the column names that are differing that would be enough as I can easily access the values later on. Also it is important to remember that I may not know the column names of all the columns, so basically I somehow must utilize user_tab_columns in the process.
Any help appreciated.
Edited by: 894302 on May 1, 2013 10:35 AMHi,
894302 wrote:
There is nothing wrong with it. Here you have added all the columns in the decode statement as you already know all the column names. What if there is a table whose column names are unknown i.e I can pass the table as a parameter to a procedure and I would need to loop through all the columns and then perform this operation.Table- and column names must be hard-coded into the query. If you want to figure out what the columns are at run time, given only hte table name, then you need dynamic SQL.
All the column names are in the data dictionary view all_tab_columns. You can easily loop through them to build exactly as many lines like
DECODE (a.row_id, b.row_id, NULL, 'row_id,') ||as you need in the SELECT clause. The FROM clause is dynamic, too: it has the variable table name in 2 places.
But i am not sure if it worth the effort to do it on the database side. Probably easier to do it on the middle tier such as .NET, which where the business logic is implemented in my company.I don't know much about .NET, so I can't compare them
It's not very hard to do in PL/SQL (as dynamic SQL goes).
Edited by: Frank Kulash on May 1, 2013 4:39 PM
Here's a function that does the dynamic SQL:
CREATE OR REPLACE FUNCTION different_columns
( in_table_name IN VARCHAR2
, in_owner_name IN VARCHAR2 DEFAULT USER
RETURN VARCHAR2
IS
return_str VARCHAR2 (4000);
sql_str VARCHAR2 (1000);
BEGIN
sql_str := 'SELECT RTRIM ( ';
FOR c IN ( SELECT column_name
, ROW_NUMBER () OVER (ORDER BY column_id DESC) AS r_n
FROM all_tab_columns
WHERE owner = in_owner_name
AND table_name = in_table_name
ORDER BY column_id
LOOP
sql_str := sql_str || ' DECODE (a.'
|| c.column_name
|| ', b.'
|| c.column_name
|| ', NULL, '''
|| c.column_name
|| ', '')';
IF c.r_n > 1
THEN
sql_str := sql_str || ' ||';
END IF;
sql_str := sql_str || CHR (10);
END LOOP;
sql_str := sql_str || ' , '', ''' || CHR (10)
|| ' )' || CHR (10)
|| 'FROM "' || in_owner_name
|| '"."' || in_table_name
|| '" a' || CHR (10)
|| 'JOIN "' || in_owner_name
|| '"."' || in_table_name
|| '" b ON a.ROWID < b.ROWID';
-- dbms_output.put_line (sql_str); -- for debugging
EXECUTE IMMEDIATE sql_str INTO return_str;
RETURN return_str;
END different_columns;
SHOW ERRORSYou can call it in SQL like this:
SELECT different_columns ('RHIT_TABLE_X') AS dc
FROM dual
;Using PL/SQL, we might not need RTRIM, at least not in the query. I'll leave that as an exercise. -
What is a efficient SQL for this query ?
Hi,
I am using 9.2 database. Suppose I am having following 2 tables
Table p having only one column i.e. 'a'. Values in this column are
a1
b1
c1
d1
Table Q having three columns a, b, c
a1, 1, 100
a1, 2, 50
b1, 1, 30
b1, 2, 40
d1, 2, 90
Table Q can be joined only using column a.
Table Q can have multiple or no records for column a in table p. Based on above sample data, I want following output
a1, 100, 50
b1, 30, 40
c1
d1, 90
Kindly tell be how can I achive this in most efiicient way !!!
thanks & regards
PJPI only have you two tracks about how do it.
If you want all the columns from p with or wihout q you have to do:
11:35:58 SQL> l
1 select p.*, q.*
2 from p,q
3* where p.a = q.a (+)
11:37:27 SQL> /
For change the order of the colums for rows you can see the url, the are more examples like that only need to search "columns for rows" in this forums.
Anyway:
with rt as
select 'a1' a, 1 b, 100 c from dual union
select 'a1', 2, 50 from dual union
select 'b1', 1, 30 from dual union
select 'b1', 2, 40 from dual union
select 'd1', 2, 90 from dual)
--select * from rt
select a, decode('1','0','0',rtrim(xmlagg(xmlelement(b, b || ',')).extract('//text()'),',')) b
, decode('1','0','0',rtrim(xmlagg(xmlelement(c, c || ',')).extract('//text()'),','))
from rt
group by a
Message was edited by:
cth
Other way:
select a, ltrim(b,',') as b, ltrim(c,',') as c
from (
select row_number() over (partition by a order by length(b) desc) as rn, a, b,c
from (select a, sys_connect_by_path(b, ',') as b,
sys_connect_by_path(c, ',') as c
from (
select row_number() over (partition by a order by b) as rn, a, b,c
from rt) y
connect by rn = prior rn + 1 and prior a = a
start with rn = 1
where rn = 1
Message was edited by:
cth -
Turning sql string (with dynamic columns) into a pipelined function
Hi guys,
I was working on an apex report the other day, and wrote the sql below (for those who don't know apex well, in an apex report you can define the columns at runtime.) When I was finished, I said to myself: "It would be great to have a pipeline function with this capability." So, the idea would be to have a sql string where the columns are created dynamically, depending on input parameters - and then be able to use this sql everywhere (oracle reports, sqlplus) through a pipelined function.
Here's the sql (simplified, of course, the data itself is actually not important - the LOOP is the key)
declare
v_sql varchar2(4000);
begin
v_sql := 'select client, ';
for i in (select employee from company_employees_view where condition = pi_parameter order by 1) loop
v_sql := v_sql || sum(decode(employee,''' || i.employee || ''', total)) "' || i.employee || '"';
end loop;
v_sql := v_sql || ', sum(total) "Total"';
v_sql := v_sql || ' from company_employees_view group by client';
end;
This sql would result in a final product like:
select client
, sum(decode(employee,'John',total) "John"
, sum(decode(employee,'Paul',total) "Paul"
, sum(decode(employee,'George',total) "George"
(and so on... this sql could have more or less columns depending on the input parameters of the function)
from company_employees_view
group by client;
I have tried feeding this sql into a ref cursor and an object, but always received an "inconsistent datatypes" message.
The object would be something like:
create or replace object rt_employee as (total number);
create or replace tt_employee as table of rt_employee;
create or replace object rt_client as (
client varchar2(100),
employee tt_employee);
create or replace tt_client as table of rt_client;
(I am not paying too much attention to syntax here.)
By the way, no hurry whatsoever, this is just for fun, take your time. I am using database XE with apex 2.1 and sql developer 1.2.
Thanks, RogerThis is the only solution I've ever seen to dynamic pipelined columns...
How to pipeline a function with a dynamic number of columns? -
Finding the column names from a table.
I am on 10g
I would like to find out the columns of a table where there are null columns in a table.....this table contains about 300 + columns where i do not want to put where condition for all the columns
is there a way i can write a sql to find?
for a given table or the results set that i need to get, i will have same results for all the rows, so it
cant be like col1 is null on row1, but col2 is not null on row2 ...they are all identical....
example table, but it has 300 + cols
F_IND H_IND P_IND DMA_IND
N N
N N
N N
N N Thanksselect count(col1), count(col2), count(col3), ...
from your table;
The results with 0s are null throughout the table (or the table has no rows). -
Custom CSS-Applying selected background for all the cols in the report
Hi,
I am trying to set a particular background for all the columns in the report(not for all the projects,so that I can avoid option of manually setting background color for complete report.For this I thought custom CSS is best option.So edited custom.css(C:\OBI11g_Middleware\Oracle_BI1\bifoundation\web\app\res\s_blafp\b_mozilla_4) file with below code and went to the Answers-> Criteria->Choose Column->style-> check "Use Custom CSS Class"->MyCell
Code used in custom.css
.MyCell { background-color: #00ff00; font-style:italic; font-weight: bold;}
Somehow I dont see the background color applied to any of the columns in report.Can anyone had successful attempt of this Custom CSS.Thanks in Advance.I am trying both the solutions.
User 979493,
I started manually writing the code instead of pasting and almost worked.In the mentioned below paths I dont have custom.css file,so I created one and manually entered below code.But does it work for only that particular column and not for all the columns.Is it supposed to work for all the columns or just that column.
For example: I have 2 cols in the report,I used "Use Custom CSS Class" -> MyCell for the first column and when I ran results it shows background color for only col1 and not for col2.I thought this feature will apply background color for all the columns in the report.Please correct me if I am wrong.
custom.css file content:
.MyCell{background-color: #00ff00;font-style:italic;font-weight:bold;}
Maybe you are looking for
-
After upgrading to iOS4 on your 3GS, are you having battery & signal issues
I was having big problems with my battery life (10% per hour at best) and also signal dropping issues from time to time. Last night though I solved all these problems... HOW ?? Via iTunes, restore your iPhone and select the option "as new iPhone" NOT
-
I lost my bookmarks, history & my most visited, how do I get them back?
I don't know what I did, but I lost my bookmarks, history & most visited, can I get these back?
-
Hi, I have an Oracle form which allows users to enter :start_date_active(mandatory) and :end_date_active (can be null). I need to check in form using SQL if there already exists a record for this date range or if there is any overlapping date ranges
-
Recalculation in excel thru java
Hi, Thru java program i can able to read and write the values into the excel sheet. but...Latest re calculating values are not available to read Example, for the following situation i am not getting right values In worksheet1 cell A1 = 10 (writing th
-
I am trying to install Skype on Windows 7.0. I get an Access Denied message and then an error 1603. I have run Microsoft fixit and am still getting the same error messages. Can anybody help me fix this? Thanks.