Sql Bigquery - concat two columns into a new column - google-bigquery

I want to concat two columns shown below into one new column.
I'm using this query:
SELECT
CONCAT( A_Bill_ID , ' ', B_BILL_ID ) AS BILL_ID
FROM
`table.tmp_140222`
From this query, the result will be like this.
My problem is I want to concat only columns that don't have a similar value so that the new column value will not duplicate two times. From the above result, the ID is duplicated since both of the columns has the same value.
Can anyone help me?
Thanks

You can use a case statement like this -
SELECT
case when A_Bill_ID = B_BILL_ID then a_bill_Id
else CONCAT(A_Bill_ID , ' ', B_BILL_ID )
end AS BILL_ID
FROM `table.tmp_140222`
If there are Null values in the initial columns, you can use IFNULL or COALEASE to replace that with an empty string. But in this case, I would suggest using this without a delimiter or writing multiple 'when' statements to avoid tailing spaces in the final column -
SELECT
case when A_Bill_ID = B_BILL_ID then a_bill_Id
else CONCAT(IFNULL(A_Bill_ID), ''), "", IFNULL(B_BILL_ID, ''))
end AS BILL_ID
FROM `table.tmp_140222`

select if (
a_bill_id = b_bill_id,
a_bill_id,
concat(a_bill_id , ' ', b_bill_id )
) as bill_id
from your_table
... shows null value ....
select if (
a_bill_id = b_bill_id or (a_bill_id = b_bill_id) is null,
coalesce(a_bill_id, b_bill_id),
concat(a_bill_id , ' ', b_bill_id )
) as bill_id
from your_table

Related

sql length(null)

I have two columns: p.firstName and p.lastName.
Now I want to display the length of both names combined, the problem is, that in some fields of p.lastName the value "null" is stored.
When I try to do it like this:
LENGTH(p.firstName + p.lastName)
I get an error:
ORA-01722 invalid number
However, if I split it up
LENGTH(p.firstName) + LENGTH(p.lastName)
it doesn't give me an error message. But the length of the sum is NULL, even if the firstName does have a few characters. The NULL of p.LastName breaks it so to say.
Anyone has an idea?
You can Use IFNULL(), ISNULL(), COALESCE(), and NVL() Functions
SELECT LENGTH(COALESCE(p.firstName,'') + COALESCE(p.lastName,'')) AS Len FROM TableName
OR
SELECT LENGTH(ISNULL(p.firstName,'') + ISNULL(p.lastName,'')) AS Len FROM TableName
OR
SELECT LENGTH(IFNULL(p.firstName,'') + IFNULL(p.lastName,'')) AS Len FROM TableName
OR
SELECT LENGTH(NVL(p.firstName,'') + NVL(p.lastName,'')) AS Len FROM TableName
OR
SELECT LENGTH(p.firstName || p.lastName) AS Len FROM TableName
You may to concat columns instead using || operator:
LENGTH(p.firstName || p.lastName)
Example:
select ('abc'||null||'d') from dual; -- abcd
select length('abc'||null||'d') from dual; -- 4
Try this
select case when p.firstname is null then 0 else length(p.firstName) end +
case when p.lastName is null then 0 else
length(nickname) end from p
Oracle usually treats an empty string as NULL:
COALESCE(LENGTH(p.firstName), 0) + COALESCE(LENGTH(p.lastName),0)
I think it is much better to use it this way...
SELECT LENGTH(ISNULL(p.firstName,'') + ISNULL(p.lastName,'')) AS length FROM TableName
NOTE: Oracle behaves differently in the dealing of blank characters:
---------Oracle
SELECT LENGTH('') , LENGTH(null) FROM DUAL
--result: null,null
---------Postgress
SELECT LENGTH('') , LENGTH(null)
--result: 0,null
---------SQL Server
SELECT LEN('') , LEN(null)
--result: 0,null
---------MySQL
SELECT LENGTH('') , LENGTH(null)
--result: 0,null

Not Null - Spaces on field

I have the below query that shows me the records in Oracle that are not null but some of the records contain spaces such as '',' ', etc.
How can I modify the query so it will ignore empty spaces?
select * from table where field1 is not null
Many Thanks.
If you problem is empty or extra space you can do something like this..
select * from table where replace(field1,' ','') is not null
You should use trim or replace function
e.g.
1.
select * from table
where field1 is not null
and trim(field1) != ''
;
2.
select * from table
where field1 is not null
and replace(field1,' ')
;
p.s null is not empty data ! it is unknown.
select * from table where field1 is not null and trim(field1) <> ''

Select 2 columns in one and combine them

Is it possible to select 2 columns in just one and combine them?
Example:
select something + somethingElse as onlyOneColumn from someTable
(SELECT column1 as column FROM table )
UNION
(SELECT column2 as column FROM table )
Yes, just like you did:
select something + somethingElse as onlyOneColumn from someTable
If you queried the database, you would have gotten the right answer.
What happens is you ask for an expression. A very simple expression is just a column name, a more complicated expression can have formulas etc in it.
Yes,
SELECT CONCAT(field1, field2) AS WHOLENAME FROM TABLE
WHERE ...
will result in data set like:
WHOLENAME
field1field2
None of the other answers worked for me but this did:
SELECT CONCAT(Cust_First, ' ', Cust_Last) AS CustName FROM customer
Yes it's possible, as long as the datatypes are compatible. If they aren't, use a CONVERT() or CAST()
SELECT firstname + ' ' + lastname AS name FROM customers
The + operator should do the trick just fine. Keep something in mind though, if one of the columns is null or does not have any value, it will give you a NULL result. Instead, combine + with the function COALESCE and you'll be set.
Here is an example:
SELECT COALESCE(column1,'') + COALESCE(column2,'') FROM table1.
For this example, if column1 is NULL, then the results of column2 will show up, instead of a simple NULL.
Hope this helps!
To complete the answer of #Pete Carter, I would add an "ALL" on the UNION (if you need to keep the duplicate entries).
(SELECT column1 as column FROM table )
UNION ALL
(SELECT column2 as column FROM table )
DROP TABLE IF EXISTS #9
CREATE TABLE #9
(
USER1 int
,USER2 int
)
INSERT INTO #9
VALUES(1, 2), (1, 3), (1, 4), (2, 3)
------------------------------------------------
(SELECT USER1 AS 'column' from #9)
UNION ALL
(SELECT USER2 AS 'column' from #9)
Would then return : Result
Yes, you can combine columns easily enough such as concatenating character data:
select col1 | col 2 as bothcols from tbl ...
or adding (for example) numeric data:
select col1 + col2 as bothcols from tbl ...
In both those cases, you end up with a single column bothcols, which contains the combined data. You may have to coerce the data type if the columns are not compatible.
if one of the column is number i have experienced the oracle will think '+' as sum operator instead concatenation.
eg:
select (id + name) as one from table 1; (id is numeric)
throws invalid number exception
in such case you can || operator which is concatenation.
select (id || name) as one from table 1;
Your syntax should work, maybe add a space between the colums like
SELECT something + ' ' + somethingElse as onlyOneColumn FROM someTable
I hope this answer helps:
SELECT (CAST(id AS NVARCHAR)+','+name) AS COMBINED_COLUMN FROM TABLENAME;
select column1 || ' ' || column2 as whole_name FROM tablename;
Here || is the concat operator used for concatenating them to single column and ('') inside || used for space between two columns.
SELECT firstname || ' ' || lastname FROM users;

How do I get first name and last name as whole name in a MYSQL query?

I want to be able to do something like this
SELECT `first_name` + " " + `last_name` as `whole_name` FROM `users`
So basically I get one column back whole_name which is first_name and last_name concatenated together with a (space).
How do I do that in SQL, or more specifically, MySQL ?
http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_concat-ws
SELECT CONCAT_WS(" ", `first_name`, `last_name`) AS `whole_name` FROM `users`
You can use a query to get the same:
SELECT CONCAT(FirstName , ' ' , MiddleName , ' ' , Lastname) AS Name FROM TableName;
Note: This query return if all columns have some value if anyone is null or empty then it will return null for all, means Name will return "NULL"
To avoid above we can use the IsNull keyword to get the same.
SELECT Concat(Ifnull(FirstName,' ') ,' ', Ifnull(MiddleName,' '),' ', Ifnull(Lastname,' ')) FROM TableName;
If anyone containing null value the ' ' (space) will add with next value.
When you have three columns : first_name, last_name, mid_name:
SELECT CASE
WHEN mid_name IS NULL OR TRIM(mid_name) ='' THEN
CONCAT_WS( " ", first_name, last_name )
ELSE
CONCAT_WS( " ", first_name, mid_name, last_name )
END
FROM USER;
rtrim(lastname)+','+rtrim(firstname) as [Person Name]
from Table
the result will show lastname,firstname as one column header !

SQL Server 2008: How to find trailing spaces

How can I find all column values in a column which have trailing spaces? For leading spaces it would simply be
select col from table where substring(col,1,1) = ' ';
You can find trailing spaces with LIKE:
SELECT col FROM tbl WHERE col LIKE '% '
SQL Server 2005:
select col from tbl where right(col, 1) = ' '
As a demo:
select
case when right('said Fred', 1) = ' ' then 1 else 0 end as NoTrail,
case when right('said Fred ', 1) = ' ' then 1 else 0 end as WithTrail
returns
NoTrail WithTrail
0 1
This is what worked for me:
select * from table_name where column_name not like RTRIM(column_name)
This will give you all the records that have trailing spaces.
If you want to get the records that have either leading or trailing spaces then you could use this:
select * from table_name where column_name not like LTRIM(RTRIM(column_name))
A very simple method is to use the LEN function.
LEN will trim trailing spaces but not preceeding spaces, so if your LEN() is different from your LEN(REVERSE()) you'll get all rows with trailing spaces:
select col from table where LEN(col) <> LEN(REVERSE(col));
this can also be used to figure out how many spaces you have for more advanced logic.
SELECT * FROM tbl WHERE LEN(col) != DATALENGTH(col)
Should work also.
There's a few different ways to do this...
My favorite option, assuming your intention is to remove any leading and / or trailing spaces, is to execute the following, which will dynamically create the T-SQL to UPDATE all columns with an unwanted space to their trimmed value:
SELECT
'UPDATE [<DatabaseName>].[dbo].['+TABLE_NAME+']
SET ['+COLUMN_NAME+']=LTRIM(RTRIM(['+COLUMN_NAME+']))
WHERE ['+COLUMN_NAME+']=LTRIM(RTRIM(['+COLUMN_NAME+']));'+CHAR(13)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME LIKE '<TableName>%'
AND DATA_TYPE!='date'
ORDER BY TABLE_NAME,COLUMN_NAME
If you really need to identify them though, try one of these queries:
SELECT *
FROM [database].[schema].[table]
WHERE [col1]!=LTRIM(RTRIM([col1]))
More dynamic SQL:
SELECT 'SELECT ''['+TABLE_NAME+'].['+COLUMN_NAME+']'',*
FROM [<your database name>].[dbo].['+TABLE_NAME+']
WHERE ['+COLUMN_NAME+'] LIKE ''% ''
OR ['+COLUMN_NAME+'] LIKE '' %'';
GO
'
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME LIKE '<filter table name as desired>%'
AND DATA_TYPE!='date'
Here's an alternative to find records with leading or trailing whitespace, including tabs etc:
SELECT * FROM tbl WHERE NOT TRIM(col) = col
Try this:
UPDATE Battles
SET name = CASE WHEN (LEN(name+'a')-1)>LEN(RTRIM(name))
THEN REPLICATE(' ', (LEN(name+'a')-1)- LEN(RTRIM(name)))+RTRIM(name)
ELSE name
END
Spaces are ignored in SQL Server so for me even the leading space was not working .
select col from table where substring(col,1,1) = ' '
wont work if there is only one space (' ') or blank ('')
so I devised following:
select * from [table] where substring(REPLACE(col, ' ', '#'),1,1) = '#'
Here is another alternative for trailing spaces.
DECLARE #VALUE VARCHAR(50) = NULL
DECLARE #VALUE VARCHAR(50) = ' '
IF ((#VALUE IS NOT NULL) AND (LTRIM(RTRIM(#VALUE)) != ''))
BEGIN
SELECT 'TRUE'
END
ELSE
BEGIN
SELECT 'FALSE'
END
I have found the accepted answer a little bit slower:
SELECT col FROM tbl WHERE col LIKE '% ';
against this technique:
SELECT col FROM tbl WHERE ASCII(RIGHT([value], 1)) = 32;
The idea is to get the last char, but compare its ASCII code with the ASCII code of space instead only with ' ' (space). If we use only ' ' space, an empty string will yield true:
DECLARE #EmptyString NVARCHAR(12) = '';
SELECT IIF(RIGHT(#EmptyString, 1) = ' ', 1, 0); -- this returns 1
The above is because of the Microsoft's implementation of string comparisons.
So, how fast exactly?
You can try the following code:
CREATE TABLE #DataSource
(
[RowID] INT PRIMARY KEY IDENTITY(1,1)
,[value] NVARCHAR(1024)
);
INSERT INTO #DataSource ([value])
SELECT TOP (1000000) 'text ' + CAST(ROW_NUMBER() OVER(ORDER BY t1.number) AS VARCHAR(12))
FROM master..spt_values t1
CROSS JOIN master..spt_values t2
UPDATE #DataSource
SET [value] = [value] + ' '
WHERE [RowID] = 100000;
SELECT *
FROM #DataSource
WHERE ASCII(RIGHT([value], 1)) = 32;
SELECT *
FROM #DataSource
WHERE [value] LIKE '% ';
On my machine there is around 1 second difference:
I have test it on table with 600k rows, but larger size, and the difference was above 8 seconds. So, how fast exactly will depend on your real case data.
Another way to achieve this by using CHARINDEX and REVERSE like below:
select col1 from table1
WHERE charindex(' ', reverse(col1)) = 1
See example Here
Simple use below query to get values having any number of spaces in begining or at end of values in column.
select * from table_name where column_name like ' %' or column_name like '% ';
We can try underscore to find the entries which are blanks,though not an accurate solution like using '% %' or ' ', But I could find entries which are blanks.
select col_name from table where col_name like '_'