how to modify this particular query? - sql

SELECT * FROM foobar
WHERE userid != '100' AND col1 REGEXP '[[:<:]]test[[:>:]]'
OR userid != '100' AND col2 REGEXP '[[:<:]]test[[:>:]]'
OR userid != '100' AND col3 REGEXP '[[:<:]]test[[:>:]]'
This query is working fine for me. It will filter basically on two criteria
where col1 or col2 or col3 have "test" and
userid is not 100.
I have another col4 which I want that, other than the above two condition, it must filter out those results where col4 = 'y'
How should I modify this above query?

You have an error in your query, You need to change the second col2 to col3. It's easier to see the error if you reformat your code:
SELECT * FROM foobar
WHERE (userid != '100' AND col1 REGEXP '[[:<:]]test[[:>:]]') OR
(userid != '100' AND col2 REGEXP '[[:<:]]test[[:>:]]') OR
(userid != '100' AND col2 REGEXP '[[:<:]]test[[:>:]]')
I've also added parentheses to make the evaluation order clear. You can rewrite your query to avoid repeating the expression userid != '100'. Then just add your missing clause:
SELECT * FROM foobar
WHERE userid != '100'
AND col4 <> 'y'
AND (
col1 REGEXP '[[:<:]]test[[:>:]]' OR
col2 REGEXP '[[:<:]]test[[:>:]]' OR
col3 REGEXP '[[:<:]]test[[:>:]]'
)

Something like this? You could also separate out the userid != '100' since it is common to the three checks.
SELECT *
FROM foobar
WHERE userid != '100'
AND (col1 REGEXP '[[:<:]]test[[:>:]]'
OR col2 REGEXP '[[:<:]]test[[:>:]]'
OR col3 REGEXP '[[:<:]]test[[:>:]]' )
AND col4 != 'y'

SELECT *
FROM foobar
WHERE userid != '100'
AND (col1 REGEXP '[[:<:]]test[[:>:]]'
OR col2 REGEXP '[[:<:]]test[[:>:]]'
OR col3 REGEXP '[[:<:]]test[[:>:]]')
AND col4 <> 'y'

Try this:
SELECT *
FROM foobar
WHERE col4 = 'y'
OR (
userid != '100'
AND (
col1 REGEXP '[[:<:]]test[[:>:]]'
OR
col2 REGEXP '[[:<:]]test[[:>:]]'
OR
col2 REGEXP '[[:<:]]test[[:>:]]'
)
)

SELECT * FROM foobar WHERE
(userid != '100') AND
(col1 REGEXP '[[:<:]]test[[:>:]]' OR userid != '100' OR col2 REGEXP '[[:<:]]test[[:>:]]' OR col2 REGEXP '[[:<:]]test[[:>:]]')
AND col4 <> 'y'

Related

How to declare a variable inside an Oracle select statement

I have this Oracle SQL request:
SELECT col1,
col2,
DECODE(
SUM(CASE WHEN col3='A' AND col4='+' THEN col5 ELSE 0 END),
NULL,
0,
SUM(CASE WHEN col3='A' AND col4='+' THEN col5 ELSE 0 END)
)
FROM mytable
group by col1, col2;
I am asking if there is a way to declare a kind of variable and have something like this:
SELECT col1,
col2,
DECODE(
myVariable,
NULL,
0,
myVariable
)
FROM mytable
group by col1, col2;
no, but you could do a subquery:
SELECT col1,
col2,
DECODE(
SUM(myColumn),
NULL,
0,
SUM(myColumn)
)
FROM (
SELECT
col1,
col2,
CASE WHEN col3='A' AND col4='+' THEN col5 ELSE 0 END myColumn
FROM mytable
) a
group by col1, col2;
You can simlpy use coalesce() (or nvl()) instead of decode().
SELECT col1,
col2,
coalesce(sum(CASE
WHEN col3 = 'A'
AND col4 = '+' THEN
col5
ELSE
0
END),
0)
FROM mytable
GROUP BY col1,
col2;
You can use coalesce(). I think this is sufficient:
select col1, col2,
coalesce(sum(case when col3 = 'A' and col4 = '+' then col5 end), 0)
from mytable
group by col1, col2;
In actual fact, this expression:
sum(case when col3 = 'A' and col4 = '+' then col5 else 0 end)
Cannot return NULL in a query with a group by -- every group has at least one row and the else guarantees a 0 returns rather than NULL.
So, this should also do what you want:
select col1, col2,
sum(case when col3 = 'A' and col4 = '+' then col5 end)
from mytable
group by col1, col2;
Yes you can use substitution variables:
SELECT col1,
col2,
DECODE(
&&myVariable,
NULL,
0,
&&myVariable
)
FROM mytable
group by col1, col2;
More info here Oracle SQL*Plus Substitution Variables

combine distinct row values into a string - sql

I would like to take cells in every row and make them into a string of names... My method already deals with casing.
For example, the table;
'john' | | 'smith' | 'smith'
'john' | 'paul' | | 'smith'
'john' | 'john' | 'john' |
returns:
'john smith'
'john paul smith'
'john'
This would need to run postgreSQL 8.2.15 of postgres so I can't make use of potentially useful functions like CONCAT, and data is in a greenplum db.
Alternatively, a method to directly delete duplicate tokens in a list of strings would let me achieve the larger objective. For example:
'john smith john smith'
'john john smith'
'smith john smith'
returns
'john smith'
'john smith'
'smith john'
The order of the tokens is not important, as long as all the unique values are returned, once only.
Thanks
Normalize your table structure, select distinct name values from that table, create a function to aggregate strings (see, e.g., How to concatenate strings of a string field in a PostgreSQL 'group by' query?), and apply that function. Except for the aggregate function creation, this could all be done in a single statement or view.
I've come up with a solution for you! :)
The following query returns the four columns (which I named col_1,2,3and 4) and removes the duplicates by joining the test_table with itself.
Here is the code:
SELECT t1.col_1, t2.col_2, t3.col_3, t4.col_4
FROM (
SELECT id, col_1
FROM test_table
) AS t1
LEFT JOIN (
SELECT id, col_2
FROM test_table
) as t2
ON (t2.id = t1.id and t2.col_2 <> t1.col_1)
LEFT JOIN (
SELECT id, col_3
FROM test_table
) as t3
ON (t3.id = t1.id and t3.col_3 <> t1.col_1 and t3.col_3 <> t2.col_2)
LEFT JOIN (
SELECT id, col_4
FROM test_table
) as t4
ON (t4.id = t1.id and t4.col_4 <> t1.col_1 and t4.col_4 <> t2.col_2 and t4.col_4 <> t3.col_3);
If you want to obtain the final string, you just substitute the "SELECT" row with this one:
SELECT trim(both ' ' FROM (COALESCE(t1.col_1, '') || ' ' || COALESCE(t2.col_2, '') || ' ' || COALESCE(t3.col_3, '') || ' ' || COALESCE(t4.col_4, '')))
this should work with your version of postgres, according with the docs:
[for the trim and concatenation functions]
https://www.postgresql.org/docs/8.2/static/functions-string.html
//***************************************************
[for the coalesce function]
https://www.postgresql.org/docs/8.2/static/functions-conditional.html
Please let me know if I've been of help :)
P.S. Your question sounds like a bad database design: I would have those columns moved on a table in which you could do this operation by using a group by or something similar. Moreover I would do the string concatenation on a separate script.
But that's my way of doing :)
I would do this by unpivoting the data and then reaggregation:
select id, string_agg(distinct col)
from (select id, col1 from t union all
select id, col2 from t union all
select id, col3 from t union all
select id, col4 from t
) t
where col is not null
group by id;
This assumes that each row has an unique id.
You can also use a giant case:
select concat_ws(',',
col1,
(case when col2 <> col1 then col2 end),
(case when col3 <> col2 and col3 <> col1 then col3 end),
(case when col4 <> col3 and col4 <> col2 and col4 <> col1 then col4 end)
) as newcol
from t;
In ancient versions of Postgres, you can phrase this as:
select trim(leading ',' from
(coalesce(',' || col1, '') ||
(case when col2 <> col1 then ',' || col2 else '' end) ||
(case when col3 <> col2 and col3 <> col1 then ',' || col3 else '' end),
(case when col4 <> col3 and col4 <> col2 and col4 <> col1 then ',' || col4 else '' end)
)
) as newcol
from t;

SQL Server : Reuse calculated variable in select clause

I have the following table structure:
col1 col2 col3 col4
-------------------------------
aK Mbcd ABc defgh
col2, col3 and col4 columns are of type varchar(100) and col1 has type varchar(500).
I need a select query to have the output as following
col1 col2 col3 col4
-------------------------------
aK,Mb cd,A Bc,d efgh
Logic is explained as mentioned below:
In the result, Col2, col3 and col4 can have maximum 4 characters but col1 can have more than 4 characters upto 100.
If any column has more characters, last 4 characters will be retained in the same column and other extra columns will be concatenated with previous column's value separated by comma , and the same rule will be applied on the concatenated values as well.
I've written the following T-SQL statement. It works fine for last two columns. But I want to use new calculated value of col3 to strip out extra characters after adding some from col4
SELECT
CASE
WHEN X.Col4Length > 4
THEN concat(X.col3, ',', substring(x.col4, 0, X.Col4Length - 3))
ELSE X.col3
END AS col3,
CASE
WHEN X.Col4Length > 4
THEN substring(x.col4, X.Col4Length - 3, x.Col4Length)
ELSE X.col4
END AS col4
FROM
(SELECT
Col1, Col2, Col3, Col4,
Len(Col1) AS Col1Length,
Len(Col2) AS Col2Length,
Len(Col3) AS Col3Length,
Len(Col4) AS Col4Length
FROM
mytable) X
My try with a simple sub-query
with t1 as (
select 'aK' col1, 'Mbcd' col2, 'ABc' col3, 'defgh' col4
---
SELECT LEFT(col, LEN(col) - 12) col1,
RIGHT(LEFT(col, LEN(col) - 8), 4) col2,
RIGHT(LEFT(col, LEN(col) - 4), 4) col3,
RIGHT(col, 4) AS col4
FROM
(
SELECT col1+','+col2+','+col3+','+col4 AS col
FROM t1
) t;
You want to reuse calculated variables
There are two set-based /inline / adhoc approaches (and many more ugly procedural):
CTEs to do this for the whole set in advance
CROSS APPLY for the same on row level
Try it like this (CTE approach)
DECLARE #tbl TABLE(col1 VARCHAR(100),col2 VARCHAR(100),col3 VARCHAR(100),col4 VARCHAR(100));
INSERT INTO #tbl VALUES
('aK','Mbcd','ABc','defgh')
,('123456','abc','3456','123456789');
WITH ResolveCol4 AS
(
SELECT *
,RIGHT(col4,4) AS Col4_resolved
,col3 + ',' + CASE WHEN LEN(col4)>4 THEN SUBSTRING(col4,1,LEN(col4)-4) ELSE '' END AS col3_New
FROM #tbl
)
,ResolveCol3 AS
(
SELECT *
,RIGHT(col3_New,4) AS Col3_resolved
,col2 + ',' + CASE WHEN LEN(col3_New)>4 THEN SUBSTRING(col3_New,1,LEN(col3_New)-4) ELSE '' END AS col2_New
FROM ResolveCol4
)
,ResolveCol2 AS
(
SELECT *
,RIGHT(col2_New,4) AS Col2_resolved
,col1 + ',' + CASE WHEN LEN(col2_New)>4 THEN SUBSTRING(col2_New,1,LEN(col2_New)-4) ELSE '' END AS col1_New
FROM ResolveCol3
)
SELECT col1_new,Col2_resolved,Col3_resolved,Col4_resolved
FROM ResolveCol2
The result
aK,Mb cd,A Bc,d efgh
123456,abc,34 56,1 2345 6789

Is there any way to print the Query result horizontally in Oracle DB

Select * from TABLENAME WHERE "CLAUSE"
It will print the result in a single row.
Col 1 Col 2 ...... Col N
Val 1 Val 2 ...... Val N
I need
Col 1 Val 1
Col 2 Val 2
.
.
.
Col N Val N
A little time consuming to do on a regular basis, but:
select COL_NAME, COL_DATA
from (SELECT * FROM table_name
WHERE clause)
unpivot ( COL_NAME FOR COL_DATA IN ( COL1 as 'COL1'
,COL2 as 'COL2'
,COL3 as 'COL3'
,COL4 AS 'COL4')
)
Bear in mind that you also need to cast all of the values to the same data-type as Oracle won't mix datatypes in the same column, so if COL1-3 are number, but COL4 is varchar, then you would
select COL_NAME, COL_DATA
from (SELECT * FROM table_name
WHERE clause)
unpivot ( COL_NAME FOR COL_DATA IN ( TO_CHAR(COL1) as 'COL1'
,TO_CHAR(COL2) as 'COL2'
,TO_CHAR(COL3) as 'COL3'
,COL4 AS 'COL4')
)
select 'col 1', col1 from TABLENAME WHERE "CLAUSE"
UNION ALL
select 'col 2', col2 from TABLENAME WHERE "CLAUSE"
UNION ALL
...
select 'col n', coln from TABLENAME WHERE "CLAUSE"
order by 1

Substring sql query

The following query would return
PR-2014-00006-02
Query:
select PRItemNo
from tPRItem
order by PRItemNo ASC
I want to sub string such as I will return the following result
col1 col2 col3 col4
PR 2014 00006 02
Use PARSENAME
--Using PARSENAME
SELECT PARSENAME(REPLACE(PRItemNo ,'-','.'),4) col1,
PARSENAME(REPLACE(PRItemNo ,'-','.'),3) col2,
PARSENAME(REPLACE(PRItemNo ,'-','.'),2) col3,
PARSENAME(REPLACE(PRItemNo ,'-','.'),1) col4
FROM Table1
Fiddle Demo
Output
COL1 COL2 COL3 COL4
PR 2014 00006 02
declare #t VARCHAR(30)= 'PR-2014-00006-02'
SELECT SUBSTRING(#t,CHARINDEX(#t,'-'),3),
SUBSTRING(substring(#t, charindex('-',#t) + 1,len(#t) - charindex('-',#t)),0,CHARINDEX('-',#t)+2),
RIGHT(substring(#t, charindex('-',#t) + 1,len(#t) - charindex('-',REVERSE(#t))-CHARINDEX('-',#t)),5),
REVERSE(LEFT(reverse(#t), charindex('-', reverse(#t)) - 1))