Concatenate columns with distinct values in oracle
Hello Gurus,
My table structre look like follwoing:
TankListUS TankListCanada TankListIndia
T111||T222 T444||T222 T555
Now when I run the query:
select (TL.TankListUS || '||' || TL.TankListCanada || '||' || TL.TankListIndia)as "OverallSummary" from TankListTL
I get output as
T111||T222||T444||T222||T555
But I don't need duplicate of tanks. I need my output as:
T111||T222||T444||T555
Is this possible?
May be this can be done in regexp..
If you are in 11g, I just tried hard way... (split, remove dups and concatenate again....) -- not elegant, but works for your test case. (this can be simplified as well )
WITH t AS
(SELECT 'T111||T222' tanklistus,
'T444||T222' tanklistcanada,
'T555' tanklistindia
FROM DUAL),
tt AS
(SELECT REPLACE (
TL.TankListUS
|| ','
|| TL.TankListCanada
|| ','
|| TL.TankListIndia,
'||',
OverallSummary
FROM t tl),
ttt AS
( SELECT LEVEL lvl,
REGEXP_SUBSTR (tt.OverallSummary,
'[^,]+',
1,
LEVEL)
LETTER
FROM tt
CONNECT BY LEVEL <= REGEXP_COUNT (tt.OverallSummary, ',') + 1)
SELECT listagg (letter, '||') WITHIN GROUP (ORDER BY lvl) str
FROM (SELECT lvl,
ROW_NUMBER () OVER (PARTITION BY letter ORDER BY 1) rnk,
letter
FROM ttt)
WHERE rnk = 1
Output:
STR
T111||T222||T444||T555
Cheers,
Manik.
Similar Messages
-
Row To Column with distinct values
Hi Oracle Gurus,
Please help me on this regard.
A table has columns statuscode,reasoncode,date with valid values as
statuscode -> status1,status2,status3,status4,status5
reasoncode -> a,b,c,d,e
Date will be passed by runtime.
Requirement is to take the stage report of statuscode by reasoncode.
i.e., if status1 has value in reason it has to show the count else return null for eg. if status1 statuscode has a, b reasoncode report wil show like below.
a b c d e
status1 1 1
status2 2 2 1
status3 4 5 5 2 3
status4 3 2 2
status5 2 2
Advanace thanx for the GurusIsn't this a duplicate to the following thread posted by another user?
Rows into columns -
To overcome column with null value-urgent
hai all,
when i query i get column with null value.
how to solve it?
thank in advance.
rcs
SQL> DESC SCOTT.CB1;
Name Null? Type
ID NUMBER
SUPCODE NUMBER
SUPLNAME VARCHAR2(100)
NAME VARCHAR2(100)
ITEMCODE VARCHAR2(10)
RECDOC NUMBER
RECDATE VARCHAR2(10)
TOTVALUE NUMBER
QTY NUMBER
CB_IPNO NUMBER
CB_VNNO NUMBER
CB_VDT VARCHAR2(10)
CB_AMT NUMBER
RECDOC_GR VARCHAR2(30)
RECDATE_GR DATE
SUPCODE_GR VARCHAR2(10)
TABLE LOOK LIKE THIS (NOT ALL DATA IN SAME ROW, BECUSE I INSERTED LAST 3 COLUMN VALUES):
ID SUPCODE SUPLNAME NAME ITEMCODE RECDOC RECDATE TOTVALUE QTY CB_IPNO CB_VNNO CB_VDT CB_AMT RECDOC_GR RECDATE_GR SUPCODE_GR
2015 AAAA 04117 9083 10545.6 78
2016 BBBB 04609 9087 25200 3600
2017 GGGG 04609 9088 28175 4025
2018 36591371.64 2565017.27
00001/07-08 02/04/2007 14020362
00002/07-08 02/04/2007 14020362
00003/07-08 02/04/2007 14010254
00004/07-08 02/04/2007 14010254
00005/07-08 02/04/2007 14021458
SQL> SELECT DISTINCT ID, SUPCODE_GR, NAME, ITEMCODE, RECDOC, RECDATE_GR, TOTVALUE, QTY FROM SCOTT.CB
1;
ID SUPCODE_GR
NAME
ITEMCODE RECDOC RECDATE_G TOTVALUE QTY
1
PRO.AT.ALU.POWDER UNCOATED
04609 15 51975 7425
2
PEN, GEL PEN
07969 17 154 11
ID SUPCODE_GR
I NEED RESULT AS FOLLOWS (ALL RESPECTIVE DDATA IN ONE LINE NOW NOT LIKE THAT):
ID SUPCODE SUPLNAME NAME ITEMCODE RECDOC RECDATE TOTVALUE QTY CB_IPNO CB_VNNO CB_VDT CB_AMT RECDOC_GR RECDATE_GR SUPCODE_GR
2015 AAAA 04117 9083 10545.6 78 00001/07-08 02/04/2007 14020362
============Even accounting for the formatting, I'm not sure I even understand the question. It could be any number of different problems or non-problems.
-
Sql query slowness due to rank and columns with null values:
Sql query slowness due to rank and columns with null values:
I have the following table in database with around 10 millions records:
Declaration:
create table PropertyOwners (
[Key] int not null primary key,
PropertyKey int not null,
BoughtDate DateTime,
OwnerKey int null,
GroupKey int null
go
[Key] is primary key and combination of PropertyKey, BoughtDate, OwnerKey and GroupKey is unique.
With the following index:
CREATE NONCLUSTERED INDEX [IX_PropertyOwners] ON [dbo].[PropertyOwners]
[PropertyKey] ASC,
[BoughtDate] DESC,
[OwnerKey] DESC,
[GroupKey] DESC
go
Description of the case:
For single BoughtDate one property can belong to multiple owners or single group, for single record there can either be OwnerKey or GroupKey but not both so one of them will be null for each record. I am trying to retrieve the data from the table using
following query for the OwnerKey. If there are same property rows for owners and group at the same time than the rows having OwnerKey with be preferred, that is why I am using "OwnerKey desc" in Rank function.
declare @ownerKey int = 40000
select PropertyKey, BoughtDate, OwnerKey, GroupKey
from (
select PropertyKey, BoughtDate, OwnerKey, GroupKey,
RANK() over (partition by PropertyKey order by BoughtDate desc, OwnerKey desc, GroupKey desc) as [Rank]
from PropertyOwners
) as result
where result.[Rank]=1 and result.[OwnerKey]=@ownerKey
It is taking 2-3 seconds to get the records which is too slow, similar time it is taking as I try to get the records using the GroupKey. But when I tried to get the records for the PropertyKey with the same query, it is executing in 10 milliseconds.
May be the slowness is due to as OwnerKey/GroupKey in the table can be null and sql server in unable to index it. I have also tried to use the Indexed view to pre ranked them but I can't use it in my query as Rank function is not supported in indexed
view.
Please note this table is updated once a day and using Sql Server 2008 R2. Any help will be greatly appreciated.create table #result (PropertyKey int not null, BoughtDate datetime, OwnerKey int null, GroupKey int null, [Rank] int not null)Create index idx ON #result(OwnerKey ,rnk)
insert into #result(PropertyKey, BoughtDate, OwnerKey, GroupKey, [Rank])
select PropertyKey, BoughtDate, OwnerKey, GroupKey,
RANK() over (partition by PropertyKey order by BoughtDate desc, OwnerKey desc, GroupKey desc) as [Rank]
from PropertyOwners
go
declare @ownerKey int = 1
select PropertyKey, BoughtDate, OwnerKey, GroupKey
from #result as result
where result.[Rank]=1
and result.[OwnerKey]=@ownerKey
go
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 -
Update column with ROW_NUMBER() value
I have a column that I would like to update with a ROW_NUMBER() value partitioned by a specific column.
CREATE TABLE ##tmp (id INT NULL,
value1 VARCHAR(10),
value2 VARCHAR(10))
INSERT INTO ##tmp (value1,
value2)
VALUES ('A', 'asdfasdf'),
('A', 'asdf'),
('A', 'VC'),
('B', 'aasdf'),
('C', 'sdfgs'),
('C', 'xdfbhsdty'),
('C', '23sdgfg'),
('C', '234')
-- update the ID column with the values below
SELECT ROW_NUMBER() OVER (PARTITION BY Value1 ORDER BY Value2),
Value1,
Value2
FROM ##tmp
I have 14 million records. Can someone explain the best way to do this? Does the ORDER BY destroy performance for this many records?
Thanks!CREATE TABLE ##tmp (id INT NULL,
value1 VARCHAR(10),
value2 VARCHAR(10))
INSERT INTO ##tmp (value1,
value2)
VALUES ('A', 'asdfasdf'),
('A', 'asdf'),
('A', 'VC'),
('B', 'aasdf'),
('C', 'sdfgs'),
('C', 'xdfbhsdty'),
('C', '23sdgfg'),
('C', '234')
-- update the ID column with the values below
; with cte as (
SELECT ROW_NUMBER() OVER (PARTITION BY Value1 ORDER BY Value2) as RowNumber,
Value1,
Value2
FROM ##tmp
update cte
set Id = RowNumber;
Russel Loski, MCT, MCSE Data Platform/Business Intelligence. Twitter: @sqlmovers; blog: www.sqlmovers.com -
Document library view: Group by a column with multiple values
I have a document library which has a managed metadata column.
I would like to create a view which groups the documents by this managed metadata column.
The managed metadata column can have multiple values.
I know that this is not possible with SharePoint's group by, since it only accepts those columns which can have only one single value.
But is this possible to accomplish by some other means, e.g. Content query web part? Or is there perhaps a 3rd party solution to this?
Is it possible to change the group by settings somehow to allow Group by to function with columns with multiple values? <- this may be far fetched...Hi Pekch,
I'm assuming you have VS2010 to build the custom web part. From there you will need to figure out the following:
Get a SPList object for the Document Library (See below for code example)
Loop through all the documents in the SPList object
If you have audience targetting enabled, then you'll need to determine if the user has access to the document by checking the "Target_x0020_Audiences" column)
As you also want to group by metadata, you'll need to populate 2 datatables (one table with a column containing unique metadata values and another table with a metadata column and other document related columns). Link these two tables via a dataset
relation.
Set the dataset as the datasource for a repeater, add in some css and javascript for the group expand/collaspe and it should be close to what you need.
This will be a time consuming task if you don't know where to start or have problems figuring out how to perform a certain operation. So you may want to determine if the functionality you want is required or just a "nice to have". Good
luck and if I have some spare time, I'll create a blog post outlining how to do all the above.
I got the below code from a sharepoint blog sometime in the past and you can use it to retrieve a list.
You can use it like this: GetListByUrl(http://servername/Shared%20Documents/Forms/AllItems.aspx)
using Microsoft.SharePoint;
public SPList GetListByUrl(string listURL)
SPList list = null;
try
using (SPSite site = new SPSite(listURL))
if (site != null)
// Strip off the site url, leaving the rest
// We'll use this to open the web
string webUrl = listURL.Substring(site.Url.Length);
// Strip off anything after /forms/
int formsPos = webUrl.IndexOf("/forms/", 0, StringComparison.InvariantCultureIgnoreCase);
if (formsPos >= 0)
webUrl = webUrl.Substring(0, webUrl.LastIndexOf('/', formsPos));
// Strip off anything after /lists/
int listPos = webUrl.IndexOf("/lists/", 0, StringComparison.InvariantCultureIgnoreCase);
if (listPos >= 0)
// Must be a custom list
// Strip off anything after /lists/
webUrl = webUrl.Substring(0, webUrl.LastIndexOf('/', listPos));
else
// No lists, must be a document library.
// Strip off the document library name
webUrl = webUrl.Substring(0, webUrl.LastIndexOf('/'));
// Get the web site
using (SPWeb web = site.OpenWeb(webUrl))
if (web != null)
// Initialize the web (avoids COM exceptions)
string title = web.Title;
// Strip off the relative list Url
// Form the full path to the list
//string relativelistURL = listURL.Substring(web.Url.Length);
//string url = SPUrlUtility.CombineUrl(web.Url, relativelistURL);
// Get the list
list = web.GetList(listURL);
catch { }
return list; -
How to Add column with default value in compress table.
Hi ,
while trying to add column to compressed table with default value i am getting error.
Even i tried no compress command on table still its giivg error that add/drop not allowed on compressed table.
Can anyone help me in this .
Thanks.Aman wrote:
while trying to add column to compressed table with default value i am getting error.This is clearly explain in the Oracle doc :
"+You cannot add a column with a default value to a compressed table or to a partitioned table containing any compressed partition, unless you first disable compression for the table or partition+"
http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/statements_3001.htm#sthref5163
Nicolas. -
ORA-01400 - not null column with default value and item with authorization
I've searched - I would think someone has run into this. APEX 3.0.0.00.20 - I've created a simple form on a table. One of the column is a not null column with a default value. I have a select list on that item, but it has security on it - authorization scheme. So, it checks the user and if that user isn't of the right role, it will not even display that item. However, APEX appears to still send in the column in its sql! So, the default value is useless, it sends in null each time. Even if I set the default at the Item level, I get null. Argg. That's got to be a bug...
In debug, I do not see the item listed at all. It's not used. That's fine - but why is it trying to insert the value? I would think it would leave it off??? I think because the item is associated with a database column. But, getting around this is ugly. Having to create a hidden item for each one, and then check to see if I need to take the list value... horrible. Any way to get around this???I should add - I guess I can always put my own custom process in to replace the DML. Just seems like a simple thing - if the value doesn't appear on the debug, isn't set with any default value... don't include it in the DML.
-
Pre-populating a date/time column with the value entered in the last added item
I have a list with a column called "expected finish date". Whenever the user adds the very first item in a list, he/she should have to enter a value for this column.
I want to make all new item entries to pre-poplate this field with the value entered in the previously added item. This way, he/she wont have to re-enter the date every time (which rarely changes). How can this be done?could create a second list ("state") with column ("default finish date")...
create a workflow on main list... if column is blank/empty, pull from second list... otherwise, update second list with the value that was entered.
Or, customize the form (InfoPath or JavaScript)
Scott Brickey
MCTS, MCPD, MCITP
www.sbrickey.com
Strategic Data Systems - for all your SharePoint needs -
OBIEE 10g - Logical column with static value
I created a logical column with static numeric value in it and added it to presentation layer. The column is not showing up in Answers. All other columns I added are showing up. The issue is with this one only.
I have verified permissions on this column in presentation layer. I tried reloading server metadata in answers, restarting all services but it didn't help.
One thing I noticed this column is showing fx icon instead of Σ icon.Kid,
The fx means it is a calculated column/formula and the sigma means that you've added some aggregation type to the column.
Either way it shouldn't matter and your column should be showing up.
I would attempt to create a new column and in the fx field try entering static text and see if that allows the column to be visible after dragging it to the presentation layer subject area.
Also what is the value that you are adding? -
How to take the Average of a DATEDIFF column with NULL values?
I am building an SSRS report that can display the average of a calculated datediff column in dd/hh/mm format with the following formula:
=Avg(IIF(Fields!LastCorrectedDate.Value is nothing,0, DATEDIFF("n",cdate(Fields!LastCorrectedDate.Value),cdate(Fields!
LastSignDate.Value)) \(60*24) & ":" & DATEDIFF("n",cdate(Fields!LastCorrectedDate.Value),cdate(Fields!
LastSignDate.Value)) mod (60*24)\60 & ":" & DATEDIFF("n",cdate(Fields!LastCorrectedDate.Value),cdate(Fields!
LastSignDate.Value)) mod (60*24) - (((DATEDIFF("n",cdate(Fields!LastCorrectedDate.Value),cdate(Fields!
LastSignDate.Value)) mod (60*24))\60)*60) ))
SSRS does not raise any errors with the formula and I have used the same formula for other columns without issue. I have noticed that this column includes null values which I think may be the problem. When the reports runs, it returns #ERROR on the column
but does not give a reason why. I am using SSRS report builder with visual basic logic as opposed to embedding SQL. Any help or feedback would be greatly appreciated.Hi No Ragrets,
According to your description, you want to calculate the average for the date time difference. Right?
In Reporting Services, Avg() function is only available for numeric values. In this scenario, the DateDiff() function to calculate the minutes difference will return a number. So we can do average calculation based on the return values first. Then we format
it as a time. We have tested this case in our local environment. Please try the following expression:
=floor(avg(DateDiff("n",Fields!StartDate.Value,Fields!EndDate.Value))) \(24*60) &":"&
floor(avg(DateDiff("n",Fields!StartDate.Value,Fields!EndDate.Value))/60 mod 24 )&":"&
floor(avg(DateDiff("n",Fields!StartDate.Value,Fields!EndDate.Value))) mod 60
The result looks like below:
If you have any question, please feel free to ask.
Best Regards,
Simon Hou -
How to create a table with distinct values ?
I want to create a new table based on an existing table distinct values only, how can I avoid to create the duplicate values ?
e.g.
table1
field1 field2
0001 ABD
0001 ABD
0002 DCF
0002 DCF
new table
field1 field2
0001 ABD
0002 DCF
thankscreate table table2
as
select distinct field1,field2
from table1 -
How to update a column with different values but all other row values r sam
Hi,
I have a table like this.
Col1 col2 col3 col4
10 20 30
10 20 30
10 20 30
i need to update col4 with different values coming from other table like this
Col1 col2 col3 col4
10 20 30 xxxx
10 20 30 yyyy
10 20 30 zzzz
how can i update the table. pls let me know how to use the where condition in the update stmt.
thanks,
jay
Edited by: user2558790 on Nov 20, 2009 12:26 PMwhat is the logic for this kind of update...????
Greetings,
Sim -
ORA-01400 error on a mandatory column with Default value
Hi,
I have got a mapping, which is loading from one view to a target table. In the target table there is a column which is marked as "NOT NULL" also has got Default value. But my mapping is failing with ORA-01400 error.
Could you please guide me which setting in the mapping will make it load the default value in the target column?
Regards,
Samujjwal BasuI should add - I guess I can always put my own custom process in to replace the DML. Just seems like a simple thing - if the value doesn't appear on the debug, isn't set with any default value... don't include it in the DML.
-
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.
Maybe you are looking for
-
Has anyone installed Redhat 9 with this motherboard(Neo2 LS 865PE)? I have tried to install but installation gets stuck at hardware checking. My harddrive, graphics card are compatible. Checked on redhat website. I cannot find any info on motherboard
-
Critical Actions are not showed in Reports
I'm having a problem in displaying user analysis report in management view. I have uploaded SAP default rulesets and it does contain some defined critical actions. I can also display critical actions by user in risk analysis reports. But the problem
-
Asking to enter a device password in the access point but I don't have an access point
I installed the Intel Proseet Wireless Client and upon connection to my Linksys router a wizard comes up asking me to "enter the device password to my access point or external registrar". It displays an 8 digit number in the device password field.
-
Need documents on presentation variable...
Hi Everyone, Am struggling on concepts of presentation variable, so i really need some basic documents or website links on presentation variables to learn with examples will be really thankful. Regards s
-
Can I get a replacement iPod?
I purchased a 4th gen iPod on the 8th of September last year, so it's still covered by the one year warranty. About a month ago the iPod began to show these problems: -At times it will run slow. (This is the main problem) -I sometimes get p