I'm working in a query using JOOQ and I'm trying to output a column as a
concatenation (space separated) of other fields extracted in the same query.
Getting into detail, with the next code I try to create a select statement with a column called fullAdress by grouping all the address lines contained in the address table. So, for each field, if it's not null or empty it will be concatenated to the result (actually no space is being added).
#Override
protected List<Field<?>> selectCustomFields() {
List<Field<?>> customSelect = new ArrayList<Field<?>>();
// Fields to use in the concatenation
Field<?> field1 = field("addr.AddressLine1"), field2 = field("addr.AddressLine2"),field3 = field("addr.AddressLine3"),
field4 = field("addr.AddressLine4"), field5 = field("addr.PostalCode"), field6 = field("addr.City"),
field7 = field("addr.State"), field8 = field("addr.County"), field9 = field("addr.Country");
// Create non null/empty conditions
Condition condLine1 = field1.isNotNull().and(field1.length().ne(0));
Condition condLine2 = field2.isNotNull().and(field2.length().ne(0));
Condition condLine3 = field3.isNotNull().and(field3.length().ne(0));
Condition condLine4 = field4.isNotNull().and(field4.length().ne(0));
Condition condLine5 = field5.isNotNull().and(field5.length().ne(0));
Condition condLine6 = field6.isNotNull().and(field6.length().ne(0));
Condition condLine7 = field7.isNotNull().and(field7.length().ne(0));
Condition condLine8 = field8.isNotNull().and(field8.length().ne(0));
Condition condLine9 = field9.isNotNull().and(field9.length().ne(0));
// Concat address lines when meets condition
customSelect.add(concat(DSL.when(condLine1, field1),
DSL.when(condLine2, field2),
DSL.when(condLine3, field3),
DSL.when(condLine4, field4),
DSL.when(condLine5, field5),
DSL.when(condLine6, field6),
DSL.when(condLine7, field7),
DSL.when(condLine8, field8),
DSL.when(condLine9, field9))
.as("fullAddress"));
return customSelect;
}
JOOQ will generate the next from the previous select statement, which is giving a null value and not concatenating the fields correctly.
select
concat(
cast(case when (
addr.AddressLine1 is not null
and char_length(cast(addr.AddressLine1 as char)) <> 0
) then addr.AddressLine1 end as char),
cast(case when (
addr.AddressLine2 is not null
and char_length(cast(addr.AddressLine2 as char)) <> 0
) then addr.AddressLine2 end as char),
cast(case when (
addr.AddressLine3 is not null
and char_length(cast(addr.AddressLine3 as char)) <> 0
) then addr.AddressLine3 end as char),
cast(case when (
addr.AddressLine4 is not null
and char_length(cast(addr.AddressLine4 as char)) <> 0
) then addr.AddressLine4 end as char),
cast(case when (
addr.PostalCode is not null
and char_length(cast(addr.PostalCode as char)) <> 0
) then addr.PostalCode end as char),
cast(case when (
addr.City is not null
and char_length(cast(addr.City as char)) <> 0
) then addr.City end as char),
cast(case when (
addr.State is not null
and char_length(cast(addr.State as char)) <> 0
) then addr.State end as char),
cast(case when (
addr.County is not null
and char_length(cast(addr.County as char)) <> 0
) then addr.County end as char),
cast(case when (
addr.Country is not null
and char_length(cast(addr.Country as char)) <> 0
) then addr.Country end as char)) as `fullAddress`
from Address as `addr`
....
My questions are,
how should I create my select statement correctly?
how can I best add the space separator?
is there any better alternative to JOOQ ( when = case ) condition clause?
how should I create my select statement correctly?
You forgot the CASE .. ELSE part, or otherwise() in jOOQ:
// Concat address lines when meets condition
customSelect.add(concat(DSL.when(condLine1, field1).otherwise(""),
DSL.when(condLine2, field2).otherwise(""),
DSL.when(condLine3, field3).otherwise(""),
DSL.when(condLine4, field4).otherwise(""),
DSL.when(condLine5, field5).otherwise(""),
DSL.when(condLine6, field6).otherwise(""),
DSL.when(condLine7, field7).otherwise(""),
DSL.when(condLine8, field8).otherwise(""),
DSL.when(condLine9, field9).otherwise(""))
.as("fullAddress"));
how can I best add the space separator?
If you want an additional space separator between your address parts, you could write:
// Concat address lines when meets condition
customSelect.add(concat(DSL.when(condLine1, field1.concat(" ")).otherwise(""),
DSL.when(condLine2, field2.concat(" ")).otherwise(""),
DSL.when(condLine3, field3.concat(" ")).otherwise(""),
DSL.when(condLine4, field4.concat(" ")).otherwise(""),
DSL.when(condLine5, field5.concat(" ")).otherwise(""),
DSL.when(condLine6, field6.concat(" ")).otherwise(""),
DSL.when(condLine7, field7.concat(" ")).otherwise(""),
DSL.when(condLine8, field8.concat(" ")).otherwise(""),
DSL.when(condLine9, field9.concat(" ")).otherwise("")).trim()
.as("fullAddress"));
is there any better alternative to JOOQ ( when = case ) condition clause?
I think the approach is sound. Of course, you probably shouldn't repeat all that logic all the time, but create a loop of the sort:
List<Field<String>> list = new ArrayList<>();
for (int i = 0; i < fields.size(); i++) {
list.add(DSL.when(conditions.get(i), (Field) fields.get(i)).otherwise(""));
}
customSelect.add(concat(list.toArray(new Field[0])).trim().as("fullAddress"));
Related
I have created the below code:
with t as (select *,
case
when `2kids`= '1' then '2kids' else'' end as new_2kids,
case
when `3kids`= '1' then '3kids' else'' end as new_3kids,
case
when kids= '1' then 'kids' else'' end as kids
from test.family)
select concat_ws('/',new_2kids, new_3kids, new_kids) as 'nc_kids'
from t;
If I run this query my output will be:
nc_kids
2kids/new_3kids/
2kids//
/new_3kids/new_kids
2kids/new_3kids/new_kids
How can I remove all the unnecessary '/' which not followed by character.
For example:
nc_kids
2kids/new_3kids
2kids
new_3kids/new_kids
2kids/new_3kids/new_kids
concat_ws() ignore nulls, so you can just turn the empty strings to null values at concatenation time:
select concat_ws('/',
nullif(new_2kids, ''),
nullif(new_3kids, ''),
nullif(new_kids, '')
) as nc_kids
from t;
Better yet, fix the case expressions so they produce null values instead of empty stings in the first place:
with t as (
select f.*,
case when `2kids`= 1 then '2kids' end as new_2kids,
case when `3kids`= 1 then '3kids' end as new_3kids,
case when kids = 1 then 'kids' end as kids
from test.family f
)
select concat_ws('/',new_2kids, new_3kids, new_kids) as nc_kids
from t;
My Query
error: select is not valid at this position for this server version, expecting : '(', WITH
set #prev="SAME";
select `date`, `COL1` , `COL2` ,
if( `COL1`>`COL2` and ( (#prev="SAME") or (#prev="UP") ) ) then
"DOWN", #prev:="DOWN"
else if( `COL1` < `COL2` and ( (#prev="SAME") or (#prev="DOWN") ) ) then
"UP", #prev:="UP"
else
"SAME"
END IF
as 'sign'
from
temp;
You cannot use IF...THEN within a query. You can use IF(condition, truevalue, falsevalue) or CASE WHEN condition THEN value1 WHEN condition2 THEN value2 ELSE something END.
IF...THEN is procedural syntax.
Following is the answer, it worked:
set #prev="SAME";
select date, COL1 , COL2 ,
CASE
WHEN( COL1>COL2 and ( (#prev="SAME") or (#prev="UP") ) )
THEN
#prev:="DOWN"
WHEN( COL1 < COL2 and ( (#prev="SAME") or (#prev="DOWN") ) )
THEN
#prev:="UP"
ELSE "SAME"
END as 'sign'
from
temp;
How to use the And, OR condition in the same MySQL where query.
SELECT * FROM Table_name
WHERE filed_name = 0 AND (field1 != '' AND field2 ='')
OR (field1 = '' AND field2 != '') AND filed3 = 1;
I want to more than 2 fileds in brackets.
You can include as many conditions as you need within parentheses, but you do need to be careful with OR and you may find it necessary to combine multiple sets of conditions with parentheses. When this happens consistent formatting and use of indents can help you maintain the required logic.
SELECT *
FROM Table_name
WHERE (field_name = 0
AND (field1 != '' AND field2 ='')
)
OR (field3 = 1
AND (field1 = '' AND field2 != '')
)
;
Do note that the query above is a guess; I have assumed you need 2 sets of conditions.
SQL refer to columns (not at fields)
anyway you can use all the columns you need in each where condition
SELECT *
FROM Table_name
WHERE col0 = 0
AND col1 != ''
AND col2 =''
OR (col1 = '' AND col2 != '' AND col3 ='YOUR_VALUE')
AND col3 = 1
OR (col4 = 'your_value4' AND col5> 100 );
the parentheses are needed for change the priority in evalaution of the condition ...
How to remove a character after the character ^ from a selected rows in table?
e.g.
TABLE Things
Boat
Do^2gs
Cat^fs
^KBear
Mi^&ce
D^Rice
RESULTS:
Boat
Dogs
Cats
Bear
Mice
Dice
select case when charindex('^', col) <> 0
then stuff(col, charindex('^', col), 2, '')
else col
end
-- to handle multiple ^ up to max of 4
select t.col,
r4.col
from Things t
cross apply
(
select col = case when charindex('^', col) <> 0
then stuff(col, charindex('^', col), 2, '')
else col
end
) r1
cross apply
(
select col = case when charindex('^', r1.col) <> 0
then stuff(r1.col, charindex('^', r1.col), 2, '')
else r1.col
end
) r2
cross apply
(
select col = case when charindex('^', r2.col) <> 0
then stuff(r2.col, charindex('^', r2.col), 2, '')
else r2.col
end
) r3
cross apply
(
select col = case when charindex('^', r3.col) <> 0
then stuff(r3.col, charindex('^', r3.col), 2, '')
else r3.col
end
) r4
-- UDF to remove the ^
create function remove_chr
(
#str varchar(100)
)
returns varchar(100)
as
begin
while charindex('^', #str) <> 0
begin
select #str = case
when charindex('^', #str) <> 0
then stuff(#str, charindex('^', #str), 2, '')
else #str
end
end
return #str
end
If you are using MySQL you could use:
SELECT col,
IF(INSTR(col,'^') > 0,CONCAT(LEFT(col,INSTR(col, '^')-1),
RIGHT(col,LENGTH(col) - INSTR(col, '^')-1)), col) AS result
FROM Things;
SqlFiddleDemo
And SQL Server equivalent:
SELECT col,
IIF(CHARINDEX('^',col) > 0,CONCAT(LEFT(col,CHARINDEX('^',col)-1),
RIGHT(col,LEN(col) - CHARINDEX('^',col)-1)), col) AS result
FROM Things
LiveDemo
SQL Server 2008:
SELECT col,
CASE WHEN CHARINDEX('^',col) > 0
THEN LEFT(col,CHARINDEX('^',col)-1) + RIGHT(col,LEN(col) - CHARINDEX('^',col)-1)
ELSE col
END AS result
FROM Things;
Keep in mind that it will work only if there is none or one occurence of ^.
Here is the solution which removes any number of occurrence of '^' .
I have created a function SQL server which is not used any loop or cursor.
CREATE FUNCTION [dbo].[FnReplaceChar](#pOriginalText VARCHAR(2000))
RETURNS VARCHAR(1000)
AS
BEGIN
DECLARE #vText VARCHAR(1000)
,#vXML XML
--Convert text as XML format
SELECT #vXML = '<Root><dtl><f>' + REPLACE(#pOriginalText,'^','</f></dtl><dtl><f>^')+'</f></dtl></Root>'
--Splits words started with '^' and combines after removing character starts with '^'
SET #vText = (
SELECT '' + ACT_TEXT
FROM
(
SELECT CASE WHEN CHARINDEX('^',DOC.COL.value('f[1]','VARCHAR(100)') ,0) > 0
THEN STUFF(DOC.COL.value('f[1]','VARCHAR(100)'),CHARINDEX('^',DOC.COL.value('f[1]','VARCHAR(100)') ,0),2,'')
ELSE DOC.COL.value('f[1]','VARCHAR(100)')
END AS ACT_TEXT
FROM #vXML.nodes('/Root/dtl') DOC(COL)
)T
FOR XML PATH('')
)
RETURN #vText
END
You can use this function in your select query
SELECT dbo.[FnReplaceChar](col_Name)
FROM [Things]
I am trying to figure out how to check if a field is NULL or empty. I have this:
SELECT IFNULL(field1, 'empty') as field1 from tablename
I need to add an additional check field1 != "" something like:
SELECT IFNULL(field1, 'empty') OR field1 != "" as field1 from tablename
Any idea how to accomplish this?
Either use
SELECT IF(field1 IS NULL or field1 = '', 'empty', field1) as field1
from tablename
or
SELECT case when field1 IS NULL or field1 = ''
then 'empty'
else field1
end as field1
from tablename
If you only want to check for null and not for empty strings then you can also use ifnull() or coalesce(field1, 'empty'). But that is not suitable for empty strings.
Using nullif does the trick:
SELECT ifnull(nullif(field1,''),'empty') AS field1
FROM tablename;
How it works: nullif is returning NULL if field is an empty string, otherwise returns the field itself. This has both the cases covered (the case when field is NULL and the case when it's an empty string).
Alternatively you can also use CASE for the same:
SELECT CASE WHEN field1 IS NULL OR field1 = ''
THEN 'empty'
ELSE field1 END AS field1
FROM tablename.
You can use the IFNULL function inside the IF. This will be a little shorter, and there will be fewer repetitions of the field name.
SELECT IF(IFNULL(field1, '') = '', 'empty', field1) AS field1
FROM tablename
You can create a function to make this easy.
create function IFEMPTY(s text, defaultValue text)
returns text deterministic
return if(s is null or s = '', defaultValue, s);
Using:
SELECT IFEMPTY(field1, 'empty') as field1
from tablename
By trimming and comparing, we ensure we also take care of empty or tab or space character content in the field.
SELECT
CASE
WHEN LTRIM(RTRIM(col_1))='' or col_1 IS NULL THEN 'Not available'
ELSE col_1
END AS col_alias
FROM
my_table
SELECT * FROM (
SELECT 2 AS RTYPE,V.ID AS VTYPE, DATE_FORMAT(ENTDT, ''%d-%m-%Y'') AS ENTDT,V.NAME AS VOUCHERTYPE,VOUCHERNO,ROUND(IF((DR_CR)>0,(DR_CR),0),0) AS DR ,ROUND(IF((DR_CR)<0,(DR_CR)*-1,0),2) AS CR ,ROUND((dr_cr),2) AS BALAMT, IF(d.narr IS NULL OR d.narr='''',t.narration,d.narr) AS NARRATION
FROM trans_m AS t JOIN trans_dtl AS d ON(t.ID=d.TRANSID)
JOIN acc_head L ON(D.ACC_ID=L.ID)
JOIN VOUCHERTYPE_M AS V ON(T.VOUCHERTYPE=V.ID)
WHERE T.CMPID=',COMPANYID,' AND d.ACC_ID=',LEDGERID ,' AND t.entdt>=''',FROMDATE ,''' AND t.entdt<=''',TODATE ,''' ',VTYPE,'
ORDER BY CAST(ENTDT AS DATE)) AS ta
If you would like to check in PHP , then you should do something like :
$query_s =mysql_query("SELECT YOURROWNAME from `YOURTABLENAME` where name = $name");
$ertom=mysql_fetch_array($query_s);
if ('' !== $ertom['YOURROWNAME']) {
//do your action
echo "It was filled";
} else {
echo "it was empty!";
}