Append “tail” to multiple selects [closed] - sql

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I have multiple result rows that has following structure
select data0, data1, ..., data30 from t0
union all select data0, ..., data30 from t1
...
There are multiple result rows, many of which need
to be aligned to the length of 30. So me do following
union all select data0, data1, null, null, ..., null
Is there a convenient way to automate this kind of
task. What I want is to append tail nulls as needed.
What I do now
with nulls as (
select null as nul0, ..., null as nul30 from dual
)
And I am stuck at this point. How to append this nulls to
result rows? Number of empty columns are known.
Pls edit as appropriate, I type from mobile

How to append this nulls to result rows?
There is no built-in solution for generating a projection of an arbitrary number of columns.
This solution will take a fair amount of typing but you can semi-automate it by using a text editor which supports regex search'n'replace patterns.
with nulls as (
select cast(null as varchar2(10)) as nul0
, ...
, cast(null as varchar2(10)) as nul30
from dual
)
select t1.dat01
, t1.dat02
, nulls.nul03 as dat03
, nulls.nul04 as dat04
...
, nulls.nul30 as dat30
from t1
cross join nulls
union all
select t2.dat01
, t2.dat02
, t2.dat03
, nulls.nul04 as dat04
...
, nulls.nul30 as dat30
from t2
cross join nulls

Related

Extract name from a string [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 days ago.
Improve this question
Example:
SubNetwork=ONRM_ROOT_MO,SubNetwork=RadioNode,MeContext=BAS917L
I want to extract only RadioNode
SubNetwork=ONRM_ROOT_MO,SubNetwork=GALRNC1,MeContext=BAT045W
I want to extract only GALRNC1.
You can do it using SUBSTRING and LEFT and charindex
select LEFT(sub1, CHARINDEX(',MeContext', sub1) - 1)
from (
select
SUBSTRING(column1, charindex('SubNetwork=', column1, 2) + LEN('SubNetwork='), 20) sub1
from mytable
) as s
charindex to get the position of your word in this case it is SubNetwork=.
SUBSTRING to Extract characters from a string.
LEFT to Extract characters from a string (starting from left).
Demo here
Please try the following solution.
It is using JSON and will work starting from SQL Server 2016 onwards.
SQL
-- DDL and sample data population, start
DECLARE #tbl TABLE (id INT IDENTITY PRIMARY KEY, tokens NVARCHAR(1024));
INSERT #tbl (tokens) VALUES
(N'SubNetwork=ONRM_ROOT_MO,SubNetwork=RadioNode,MeContext=BAS917L'),
(N'SubNetwork=ONRM_ROOT_MO,SubNetwork=GALRNC1,MeContext=BAT045W');
-- DDL and sample data population, end
SELECT t.*
, SubNetwork = JSON_VALUE(j,'$.SubNetwork')
FROM #tbl AS t
CROSS APPLY (SELECT '{"' + REPLACE(REPLACE(STRING_ESCAPE('~'+tokens,'json')
,',','","')
,'=','":"') + '"}'
) AS t1(j);;
Output
id
tokens
SubNetwork
1
SubNetwork=ONRM_ROOT_MO,SubNetwork=RadioNode,MeContext=BAS917L
RadioNode
2
SubNetwork=ONRM_ROOT_MO,SubNetwork=GALRNC1,MeContext=BAT045W
GALRNC1

SQL server SELECT CASE large script [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I want to select some records from a table with CASE option
like this
SELECT col1,col2,
CASE col2
WHEN '7c6014eb0000d37090d972c0ad2520f7' THEN 'xxxxx'
WHEN '5610d19400005469af3a78d225e11cb9' THEN 'aaaaa'
WHEN '31c08eb10000ye1aa51ff5a165246604' THEN 'bbbb'
WHEN '37e543fe00016d03007f6b304edfa94e' THEN 'ccccc'
WHEN '0ca1e79f0001zde1909b64c3d1246b80' THEN 'ddddd'
WHEN '25a14c480001g491c7284b0e107a39e7' THEN 'eeeee'
+500k line ....
END AS TargetAliasColumnName
FROM table
but the problem that i have a large script +500k record,
i got just( Command(s) completed successfully.
) :/
Update:
The hole script compile in the excute area, but after executing , i got just Command(s) completed successfully. my table name is ( account) in the table there are 2 columns ( user,password) in the table there are 1 milion records, i want to to select all these records in the table but with CASE password records
It,s better to create table and put all case value pair into table .
after you can use joins to achieve your goal.
The SQL is probably too big to compile. If you add the case values to a table you will be able to do what you want.
tbl_case
key_column, case_value
7c6014eb0000737090d972c0ad2520f7 xxxxx
SELECT table.key_value, tbl_case.case value
from table
join tbl_case on table.key_value = tbl_case.key_value; ----------
Try This ,
Create another table like this
CREATE TABLE [dbo].[Table_1](
[Col2] [nvarchar](50) NULL,
[CaseVal] [nchar](10) NULL
) ON [PRIMARY]
Insert all the Distinct data what you have. Then write a sql like below
SELECT b.Col1, b.Col2, a.CaseVal TargetAliasColumnName
FROM Table_1 a inner join [dbo].[Table1] b on
a.col2=b.Col2

Usage of DISTINCT in Oracle [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
Why my query is still showing the duplicate tuples?
I want all the attributes of all distinct tuples
select distinct * from employees;
I think your approach related to NULL values and empty strings maybe the cause of the problem :
create table tab( id int, value varchar2(75));
insert into tab values(1,' ');
insert into tab values(1,' ');
insert into tab values(1,'');
insert into tab values(1,null);
select distinct * from tab;
ID VALUE
-- -----
1
1
1 (null)
select id, length(value) as value from tab;
ID VALUE
-- -----
1 2
1 1
1 (null)
1 (null)
Oracle considers '' as NULL but the empty strings with length >= 1 is not considered as NULL.
SQL Fiddle Demo
If yours columns have some " " , you'll find duplicate because
Value1 value 2 " " is not
Value1 value 2 "" nor
value1 value2 NULL
Plus, PrimaryKey is always unique so
select distinct *, is unique
Often, if you need "select unique" in table employee, there a problem of conception because every employe should appears only once (if it is a real table employe without been linking)
To fix this during import you would have to trim whitespace from the end of the string, this should take care of those 3 different characters. Note that LTRIM and RTRIM only removes "blanks" which further down in the documentation suggests that only spaces are considered. You would thus have to use a different trim function, like in the programming language you're using, to do this trimming.
If you need all distinct results for a tuple then you should not use * (all column) but explicitly select for only the columns involved in tuple
select distinct col1, col2, col3 from employees;
Typically using all column selector (*) you select also the primary key from your table that typically (by definition) is not duplicated so using select * ...
you get all the rows in table.

Handle missing data in SQL Server 2012 SELECT statement [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
create table t1 (col1 int);
Leave the table empty.
select isnull(col1,0) from t1;
I want to replace null with zeros in the above case. However, ISNULL() does not work if there are no records in the table. How can I get around this?
Maybe you can first test if the table is empty:
IF NOT EXISTS (select * from t1)
SELECT 0
ELSE select coalesce(col1,0) from t1;
Anyway, you should use COALESCE instead of ISNULL because it is standard SQL.
In case if you want to replace non existing value then surround another null check of mentioned select statement. like this
ISNULL(select isnull(col1,0) from t1,0)
COALESCE(col1, 0)
will give you the first non-NULL value from the list, which is
col1 if col1 does not contain NULL
0 if col1 contains NULL.
If no record exists in the table , your query returns EMPTY not NULL .
You can transform the EMPTY value into a NULL value and then switch it to 0 like this :
SELECT ISNULL((SELECT col1 FROM tl),0) AS col1;
When I want to return exactly one row from a table that might be empty or have an arbitrary number of rows, then I often use aggregation:
select coalesce(max(col1), 0)
from t1;
This is guaranteed to return exactly one row. It is unclear what you want when the table is not empty, however.
If you absolutely must have a value returned for an empty table, maybe something like:
if ((select COUNT(*) from t1) = 0)
begin
select 0 as col1;
end
else
begin
select isnull(col1,0) as col1 from t1;
end
The left join will get a hard coded table, OneZero, even with no rows in t1.
select isnull(t1.col1, OneZero.zero)
from ( values(0) ) as OneZero (zero)
left join t1
on 1 = 1

How to write a query that builds a string dynamically based on a 2 tables [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have 2 tables: MainTable and ControlTable.
I want to write a query that builds a string representing a file path.
File path will be built dynamically depending on a query result between two tables.
Main table has the following columns:
ControlNumber
CustomerID
CustomerStatement
The Control table has only one column: ControlNumber
I need to write a query that checks if Main table has a ControlNumber defined in Control Table.
If there is a match, I append \FolderA to my FilePath
If no match, I append \FolderB
Ending result will be something like this:
C:\Customers\FolderA or C:\Customers\FolderB
I suspect I need to use left join
How can I do that?
You're right that you want a left join. Combine that with a case...when expression to determine the value:
select
*,
case
when Control.ControlNumber is not null
then '\FolderA'
else '\FolderB'
end as FilePath
from main
left join control on main.ControlNumber = control.ControlNumber
It's not clear where the rest of the path comes from; maybe it's static and you want to concatenate it with the value from the case expression:
'c:\customers' + -- or concat() or || depending on sql dialect
case when Control.ControlNumber is not null then '\FolderA' else '\FolderB' end as FilePath
SELECT 'C:\' || CustomerID || '\FolderA'
FROM MainTable
WHERE EXISTS
( SELECT 1 FROM ControlNumber WHERE ControlTable.ControlNumber = MainTable.CustomerID )
UNION
SELECT 'C:\' || CustomerID || '\FolderB'
FROM MainTable
WHERE NOT EXISTS
( SELECT 1 FROM ControlTable WHERE ControlTable.ControlNumber = MainTable.ControlNumber)