I am moving a customer database which has a First Name, Last Name and Company Name. The current data will either have a First & Last Name or a Company name
In the new database I have a "Print Name" field which I need to combine the first and last name into, or if there is a company name present I need to use this value.
I have tried the bellow CASE WHEN expression to no avail.
SELECT
fstnam,
lstnam,
cmpnam,
CASE
WHEN csttbl.cmpnam = null THEN fstnam||' '||lstnam
ELSE csttbl.cmpnam
END as PrintName
FROM csttbl;
With the above query I only have a company name return in the print name column, not the combined First & Last Name. the returned data can be seen here https://drive.google.com/open?id=0B31ZRmFSX6rMYmNOczlRNE1lM2c
Any help would be appreciated
Change
csttbl.cmpnam = null
To
csttbl.cmpnam is null
RDBMS cannot compare null to any value, so using = with null is of no use. To compare nulls you should use is null which works on almost all RDBMS.
I would use coalesce():
SELECT fstnam, lstnam, cmpnam,
COALESCE(csttbl.cmpnam, fstnam|| ' ' || lstnam) as PrintName
FROM csttbl;
Didn't think of just concatonating the whole string as there is no First & Last name if there is a company name. COALESCE doesn't seem to work for me though so did the below
SELECT
fstnam,
lstnam,
cmpnam,
csttbl.cmpnam||fstnam|| ' ' ||lstnam as PrintName
FROM csttbl;
Related
We have below string column and having below data
and I want to find Null count present in string columns means how many times null value('') present in front of id column present in select statement
using big query.
Don't use string position.
Expected output:
count of null ('')id =3
1st row,2nd row and 5th row
Below is for BigQuery Standard SQL
#standardSQL
SELECT
FORMAT(
"count of null ('')id = %d. List of id is: %s",
COUNT(*),
STRING_AGG(CAST(ID AS STRING))
) AS output
FROM `project.dataset.table`
WHERE REGEXP_CONTAINS(String, r"(?i)''\s+(?:as|)\s+(?:id|\[id\])")
if to apply to sample data from your question - the output is
Row output
1 count of null ('')id = 3. List of id is: 1,2,5
The idea is to unify all strings to something you can query with like = "%''asid%" or regex
First replace all spaces with ''
replace "[", "]" with ''.
Make the use of " or ' consistent.
Then query with like.
For example:
select 1 from (select replace(replace(replace(replace('select "" as do, "" as [id] form table1',' ',''),'[',''),']',''),'"',"'") as tt)
where tt like ("%''asid%")
Its not a "smart" idea but its simple.
A better idea will be to save the query columns in a repeat column '"" as id' and the table in another column.
You don't need to save 'select' and 'from' this way you can query easily and also assemble a query from the data.
If I understand correctly, you want to count the number of appearances of '' in the string column.
If so, you can use regexp_extract_all():
select t.*,
(select count(*)
from unnest(regexp_extract_all(t.string, "''")) u
) as empty_string_count
from t;
I am attempting to update several values in a table based on several conditions. If a column (let's call it "name") contains some set of strings, I would like to change the name to something else. For example, if name contains two consecutive a's, like "aa", I would like to change it to just "A".
Here is my query that is currently not working:
UPDATE table
SET name = CASE name
WHEN name like "%aa%" then "A"
WHEN name like "%er%" then "E"
ELSE "Z"
END
WHERE name is not null
I know it is a non-sensical example, but I'm not great with coming up with those on the spot. The error I am currently getting is:
"No matching signature for operator CASE for argument types: STRING, BOOL, STRING, BOOL, STRING, STRING at [2:18].
Any thoughts?
Remove name from CASE name and replace double quotes " with single quotes ':
UPDATE table
SET name = CASE
WHEN name like '%aa%' then 'A'
WHEN name like '%er%' then 'E'
ELSE 'Z'
END
WHERE name is not null
P.S. in this example and your question query the word table is the name of the table not the keyword table. That means that in some databases you will have problems and you will have to put this word in quotes.
In this DEMO you can see that the query from my answer will work in MySQL database when you put word table in quotes.
In this DEMO you can see that the query from my answer will work in Oracle database when you put word table in double quotes. Also you will see that the strings(values of columns) can not be between double quotes in Oracle.
Note: Some of the databases will not cause errors if the string(column value) is between double quotes but it is better to use single quotes for this and because you have not tagged a database that you use this are some guidelines that will help you.
Remove the first name in the CASE clause:
UPDATE table
SET name = CASE WHEN name like "%aa%" then "A"
WHEN name like "%er%" then "E"
ELSE "Z"
END
WHERE name is not null
Exactly what The Impaler said,remove the first name in the CASE clause. SQL syntax does not call for the column name directly after case. For example (From W3 schools):
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
WHEN conditionN THEN resultN
ELSE result
END;
https://www.w3schools.com/sql/sql_case.asp
Good luck!
Remove the first instance of the word name
UPDATE table
SET name = CASE
WHEN name like "%aa%" then "A"
WHEN name like "%er%" then "E"
ELSE "Z"
END
WHERE name is not null
There are two ways to use case:
1) CASE WHEN name=1 THEN WHEN name=2 THEN...
2) CASE name WHEN 1 THEN WHEN 2 THEN...
In the first case it looks for the first TRUE expression, in the second for the first expression that is equal to name.
You made a mix of the two, but for the interpreter it is the second form.
Therefore, it was looking for the first expression equal to name. When it reads the first WHEN, it checks whether name is equal to the argument (name like "%aa%")
But (name like "%aa%") is a boolean, name is a string, hence the error.
I created a view for report. I imported data to the report. In columns null values are also present. If i filter one row using filter in vb.net the null values of row cannot be displayed.
For example, column names are ID, Name, Number, Place. In this some of the places number has null values I include filter ID, Name ,Number,Place. If I filter using ID the null values of number cannot be displayed.
This is the code I tried but not filter
IN FORM TextBox1.Text=""
TABLE1BindingSource.Filter = "YOUR FIELDNAME LIKE '" + TextBox1.Text.Equals (String.Empty) + "'")
Expected Result
Table
YOUR FIELDNAME
value1
value2
NULL
value3
NULL
NULL
value4
That filter doesn't make sense. This part:
TextBox1.Text.Equals(String.Empty)
is going to evaluate to Boolean, i.e. True if the TextBox is empty and False if it's not. That means that your filter ends up being:
YOUR FIELDNAME LIKE 'False'
or the like. What you should actually be doing is something like this:
Dim columnName As String
Dim fieldValue As String
'...
TABLE1BindingSource.Filter = String.Format("{0} LIKE '{1}%'", columnName, fieldValue)
Note a number of things there. Firstly, the use of String.Format to make this sort of code more readable. Secondly, the use of the actual value entered by the user and not a Boolean indicating whether that value was empty or not. Thirdly, the use of a wildcard because using LIKE without a wildcard makes no sense.
It should also be noted that that code is only going to work with text fields, because they are the only ones that get delimited by single quotes and the only ones that you can use LIKE with. If you want to filter on a numeric field or some other data type then you'll have to write your code to create the filter differently.
All,
I'm writing a query that includes a CASE statement which compares two datetime fields. If Date B is > Date A, then I'd like the query to display Date B. However, if Date B is not > Date A, then the user who will be getting the report created by the query wants the column to be blank (in other words, not contain the word 'NULL', not contain a hyphen, not contain a low values date). I've been researching this today but have not come up with a viable solution so thought I'd ask here. This is what I have currently:
CASE
WHEN B.DTE_LNP_LAST > A.DTE_PROC_ACT
THEN B.DTE_LNP_LAST
ELSE ?
END AS "DATE OF DISCONNECT"
If I put NULL where the ? is, then I get a hyphen (-) in my query result. If I omit the Else statement, I also get a hyphen in the query result. ' ' doesn't work at all. Does anyone have any thoughts?
Typically the way nulls are displayed is controlled by the client software used to display query results. If you insist on doing that in SQL, you will need to convert the date to a character string:
CASE
WHEN B.DTE_LNP_LAST > A.DTE_PROC_ACT
THEN VARCHAR_FORMAT(B.DTE_LNP_LAST)
ELSE ''
END AS "DATE OF DISCONNECT"
Replace VARCHAR_FORMAT() with the formatting function available in your DB2 version on your platform, if necessary.
You can use the coalesce function
Coalesce (column, 'text')
If the first value is null, it will be replaced by the second one.
I am working with a table that contains two versions of stored information. To simplify it, one column contains the old description of a file run while another column contains the updated standard for displaying ran files. It gets more complicated in that the older column can have multiple standards within itself. The table:
Old Column New Column
Desc: LGX/101/rpt null
null Home
Print: LGX/234/rpt null
null Print
null Page
I need to combine the two columns into one, but I also need to delete the "Print: " and "Desc: " string from the beginning of the old column values. Any suggestions? Let me know if/when I'm forgetting something you need to know!
(I am writing in Cache SQL, but I'd just like a general approach to my problem, I can figure out the specifics past that.)
EDIT: the condition is that if substr(oldcol,1,5) = 'desc: ' then substr(oldcol,6)
else if substr(oldcol,1,6) = 'print: ' then substr(oldcol,7) etc. So as to take out the "desc: " and the "print: " to sanitize the data somewhat.
EDIT2: I want to make the table look like this:
Col
LGX/101/rpt
Home
LGX/234/rpt
Print
Page
It's difficult to understand what you are looking for exactly. Does the above represent before/after, or both columns that need combining/merging.
My guess is that COALESCE might be able to help you. It takes a bunch of parameters and returns the first non NULL.
It looks like you're wanting to grab values from new if old is NULL and old if new is null. To do that you can use a case statement in your SQL. I know CASE statements are supported by MySQL, I'm not sure if they'll help you here.
SELECT (CASE WHEN old_col IS NULL THEN new_col ELSE old_col END) as val FROM table_name
This will grab new_col if old_col is NULL, otherwise it will grab old_col.
You can remove the Print: and Desc: by using a combination of CharIndex and Substring functions. Here it goes
SELECT CASE WHEN CHARINDEX(':',COALESCE(OldCol,NewCol)) > 0 THEN
SUBSTRING(COALESCE(OldCol,NewCol),CHARINDEX(':',COALESCE(OldCol,NewCol))+1,8000)
ELSE
COALESCE(OldCol,NewCol)
END AS Newcolvalue
FROM [SchemaName].[TableName]
The Charindex gives the position of the character/string you are searching for.
So you get the position of ":" in the computed column(Coalesce part) and pass that value to the substring function. Then add +1 to the position which indicates the substring function to get the part after the ":". Now you have a string without "Desc:" and "Print:".
Hope this helps.