Compare columns of same table in sql server - sql

I'm trying to compare the columns of a table and fetch the unmatched rows.Can someone help me to write a query to fetch the rows where Email_ID not in the format of Firstname.Lastname#abc.com in the below scenario.
TABLE
S.no Firstname Lastname Email_ID
701 Sean Paul Sean.Paul#abc.com
702 Mike Tyson Mike.Samuel#abc.com
703 Richard Bernard Jim.Anderson#abc.com
704 Simon Sharma Rita.sharma#abc.com

You mean something like:
select -- some columns
from table
where Email_ID <> (FirstName + '.' + Lastname + '#abc.com')
?
There is nothing in SQL to prevent comparing one column with another, and – with a little more syntax – even across rows.

Search for rows where mail address not like Concat( firstname . lastname #)
select * from tablename
where Email_ID NOT LIKE (Firstname + '.' + Lastname + '#%')

SELECT *
FROM YourTable
WHERE CHARINDEX(FirstName + '.' + LastName + '#', Email) = 0

Related

How to convert two nvarchar rows into one when one of the row is null

sorry if this is a duplicate to one of existing questions (it's so simple but I can't figure it out, I'm new).
I need to migrate some data from one table to another (different structures).
Table A have Firstname and LastName columns.
Table B have Name column
I want to do
SELECT Firstname + ' ' + LastName As Name FROM TableA
But the problem is that in table B, some rows have null value for firstname or lastname but not both (Lazy user).
When I import them into table B, the query fails because Name column is non-nullable in my new design and when I test the statement above, if firstname or lastname is null, the concated value is null.
From the reading that I've done, this is expected behavior but what can I do to get around this?
I want to save firstname or lastname if the other is null.
SELECT RTRIM(LTRIM(ISNULL(Firstname ,'') + ' ' + ISNULL(LastName,''))) AS Name
FROM TableA
This can be done with a single colaesce (return first non-null) & no need to mess about with spaces.
select
coalesce(firstname + ' ' + lastname, firstname, lastname)
from TableA
use coalesce or isnull
select COALESCE(FirstNAme, '') + ' ' + COALESCE(LastName, '') as name from TableA
SELECT isnull (Firstname, '') + ' ' isnull (LastName, '') as Name
FROM TableA

Compare Columns Where One is Similar to Part of Another

I'm trying to write a Select statement where I can see if one column is like part of another.
tblNames
ID FullName FirstName
1 Mr. John Doe, CEO John
2 Mr. Jake Doe, Exec Jake
3 Mrs. Betty Smith, Chair Jill
The query should return:
3 | Mrs.Betty Smith, Chair | Jill
However mine just returns every row in the table:
SELECT ID, FullName, FirstName
FROM tblNames
WHERE '%' + FirstName + '%' not like Fullname
Any ideas?
Reverse the where, to something like this:
Fullname not like '%' + FirstName + '%'
This worked for me:
SELECT *
FROM `table`
WHERE `col1` NOT LIKE CONCAT('%', `col2`, '%')
Found it here:
http://www.edmondscommerce.co.uk/mysql/compare-two-columns-in-mysql/
Somehow it only worked correctly with the concat-function (?).
Try this:
SELECT * FROM tblNames
WHERE ISNULL( CHARINDEX (FirstName , FullName),0) = 0
The CHARINDEX will be faster (more performant) than a LIKE clause, as it doesn't have to take wildcards into account. The sample data above with small numbers of rows won't show a performance benefit, but when in the millions of rows, CHARINDEX would perform better.
Switch the arguments to LIKE in the WHERE clause:
SELECT ID, FullName, FirstName
FROM tblNames
WHERE Fullname not like '%' + FirstName + '%'
The wildcard must be the second argument.
Oracle expects number when + is used. For string, please use the samle below :
SELECT ID, FullName, FirstName
FROM tblNames
WHERE FullName like '%' || FirstName||'%'
To compare one column of a table to a column of another table, please do the following
select a.*,table_2_col_1, table_2_col_2 from (select table_1_col_1, table_1_col_2 from table_1 where
) a, table_2 where table_1_col_1 like '%' || table_2_col_1 ||'%'
It looks OK, except you probably want to switch the order around in your where:
WHERE Fullname not like '%' + FirstName + '%'
Parentheses also would have fixed the issue.
SELECT ID, FullName, FirstName
FROM tblNames
WHERE ('%' + FirstName + '%') not like Fullname
With Google BigQuery:
Fullname NOT LIKE ('%' || FirstName || '%')

SQL Search Query for Multiple Where Clauses e.g. Firstname AND Surname

I have a SQL Search Query which works if I search on the First Name or the Surname:
SELECT MemberID, FirstName, Surname, Title + ' ' + FirstName + ' ' + Surname AS FullName
FROM Members
WHERE FirstName + Surname LIKE N'%' + 'Smith' + '%'
ORDER BY FullName
If I search for John I see all John's if I search for Smith I see all Smith's What I would like is to search for John Smith and see all John Smith's. Thanks
UPDATE:
I should have made my original post clearer. I am using vb.net and when the user enters a search term into a text box the actual query that is run is as follows:
SELECT MemberID, FirstName, Surname, Title + ' ' + FirstName + ' ' + Surname AS FullName
FROM Members
WHERE FirstName + Surname LIKE N'%' + #SearchTerm + '%'
ORDER BY FullName
I want the user to be able to type: John S and see all users called John with a Surname of S.
SELECT MemberID, FirstName, Surname, Title + ' ' + FirstName + ' ' + Surname AS FullName
FROM Members
WHERE FirstName LIKE '%john%'
AND Surname LIKE '%smith%'
ORDER BY FullName;
Based on the caveats and conditions in your comments on other questions, your best bet is going to be have two search boxes (firstname and surname) and build a query that looks something like this.
SELECT MemberID, FirstName, Surname, Title + ' ' + FirstName + ' ' + Surname AS FullName
FROM Members
WHERE FirstName like N'%' + #SearchFirst + '%' AND
Surname LIKE N'%' + #SearchSurname + '%'
ORDER BY FullName
Alternatively you could try to manually parse a single search box into first and last name before inserting the values into your query. But parsing names is a very dicey affair not entered into lightly.
SELECT MemberID, FirstName, Surname, Title + ' ' + FirstName + ' ' + Surname AS FullName
FROM Members
WHERE FirstName + Surname LIKE N'%' + 'Smith' + '%'
ORDER BY FullName
Okie, I'mma try to take a crack at this. Assuming that you want to search for last and first name.
SELECT MemberID, FirstName, Surname, Title + ' ' + FirstName + ' ' + Surname AS FullName
FROM Members
WHERE FirstName='John' AND Surname='Smith'
ORDER BY FullName
Would this work?
Unless you have data like this:
Firstname | Lastname
John Stewart | Mill
your query above with Searchterm = '%John M%' will find all the Johns whose surname begins with M, provided that you concatenate a space:
where firstname + ' ' + lastname like '%John S%'
However you won't get great performance with CONTAINS-SUBSTRING type queries (i.e. wildcard on either side of the search term). Starts-with queries can make use of an index, so it would better to write:
where firstname = 'John' -- can use an index on firstname column
and lastname like 'S%' -- can use an index on lastname column
SELECT     MemberID, FirstName, Surname, Title + ' ' + FirstName + ' ' + Surname AS FullName
FROM         Members
WHERE FirstName + ' ' + Surname LIKE N'%' + SearchTerm + '%'
ORDER BY FirstName
Here SearchTerm could be any
John Smith,
Or
John S,
Or
John,
Or simply
J

Concat two column in a select statement sql server 2005

How to Concat two column in a select statement sql server 2005?
Here is my statement Select FirstName,secondName from Table...
Now i did try concating secondName with FirstName by using
Select FirstName + ' ' + secondName from Table
But some values are NULL in secondName column for some records.. My select statement
returns NULL instead of FirstName.. I want to have FirstName if secondName is NULL ..
SELECT FirstName + ISNULL(' ' + SecondName, '') from Table
If one of your fields is numeric then you can cast it to a string as follows:
SELECT FirstName + ISNULL(' ' + SecondName, '') + ' age(' + CONVERT(nvarchar,age) + ')' from Table
do like this :
select cast( FirstName as varchar)+' '+cast( secondName as varchar) from table

How do I perform a GROUP BY on an aliased column in SQL Server?

I'm trying to perform a group by action on an aliased column (example below) but can't determine the proper syntax.
SELECT LastName + ', ' + FirstName AS 'FullName'
FROM customers
GROUP BY 'FullName'
What is the correct syntax?
Extending the question further (I had not expected the answers I had received) would the solution still apply for a CASEed aliased column?
SELECT
CASE
WHEN LastName IS NULL THEN FirstName
WHEN LastName IS NOT NULL THEN LastName + ', ' + FirstName
END AS 'FullName'
FROM customers
GROUP BY
LastName, FirstName
And the answer is yes it does still apply.
You pass the expression you want to group by rather than the alias
SELECT LastName + ', ' + FirstName AS 'FullName'
FROM customers
GROUP BY LastName + ', ' + FirstName
This is what I do.
SELECT FullName
FROM
(
SELECT LastName + ', ' + FirstName AS FullName
FROM customers
) as sub
GROUP BY FullName
This technique applies in a straightforward way to your "edit" scenario:
SELECT FullName
FROM
(
SELECT
CASE
WHEN LastName IS NULL THEN FirstName
WHEN LastName IS NOT NULL THEN LastName + ', ' + FirstName
END AS FullName
FROM customers
) as sub
GROUP BY FullName
Unfortunately you can't reference your alias in the GROUP BY statement, you'll have to write the logic again, amazing as that seems.
SELECT LastName + ', ' + FirstName AS 'FullName'
FROM customers
GROUP BY LastName + ', ' + FirstName
Alternately you could put the select into a subselect or common table expression, after which you could group on the column name (no longer an alias.)
Sorry, this is not possible with MS SQL Server (possible though with PostgreSQL):
select lastname + ', ' + firstname as fullname
from person
group by fullname
Otherwise just use this:
select x.fullname
from
(
select lastname + ', ' + firstname as fullname
from person
) as x
group by x.fullname
Or this:
select lastname + ', ' + firstname as fullname
from person
group by lastname, firstname -- no need to put the ', '
The above query is faster, groups the fields first, then compute those fields.
The following query is slower (it tries to compute first the select expression, then it groups the records based on that computation).
select lastname + ', ' + firstname as fullname
from person
group by lastname + ', ' + firstname
Given your edited problem description, I'd suggest using COALESCE() instead of that unwieldy CASE expression:
SELECT FullName
FROM (
SELECT COALESCE(LastName+', '+FirstName, FirstName) AS FullName
FROM customers
) c
GROUP BY FullName;
My guess is:
SELECT LastName + ', ' + FirstName AS 'FullName'
FROM customers
GROUP BY LastName + ', ' + FirstName
Oracle has a similar limitation, which is annoying. I'm curious if there exists a better solution.
To answer the second half of the question, this limitation applies to more complex expressions such as your case statement as well. The best suggestion I've seen it to use a sub-select to name the complex expression.
You can use CROSS APPLY to create an alias and use it in the GROUP BY clause, like so:
SELECT FullName
FROM Customers
CROSS APPLY (SELECT LastName + ', ' + FirstName AS FullName) Alias
GROUP BY FullName
SELECT
CASE
WHEN LastName IS NULL THEN FirstName
WHEN LastName IS NOT NULL THEN LastName + ', ' + FirstName
END AS 'FullName'
FROM
customers
GROUP BY
LastName,
FirstName
This works because the formula you use (the CASE statement) can never give the same answer for two different inputs.
This is not the case if you used something like:
LEFT(FirstName, 1) + ' ' + LastName
In such a case "James Taylor" and "John Taylor" would both result in "J Taylor".
If you wanted your output to have "J Taylor" twice (one for each person):
GROUP BY LastName, FirstName
If, however, you wanted just one row of "J Taylor" you'd want:
GROUP BY LastName, LEFT(FirstName, 1)
If you want to avoid the mess of the case statement being in your query twice, you may want to place it in a User-Defined-Function.
Sorry, but SQL Server would not render the dataset before the Group By clause so the column alias is not available. You could use it in the Order By.
In the old FoxPro (I haven't used it since version 2.5), you could write something like this:
SELECT LastName + ', ' + FirstName AS 'FullName', Birthday, Title
FROM customers
GROUP BY 1,3,2
I really liked that syntax. Why isn't it implemented anywhere else? It's a nice shortcut, but I assume it causes other problems?
SELECT
CASE WHEN LastName IS NULL THEN FirstName
WHEN LastName IS NOT NULL THEN LastName + ', ' + FirstName
END AS 'FullName'
FROM customers GROUP BY 1`
For anyone who finds themselves with the following problem (grouping by ensuring zero and null values are treated as equals)...
SELECT AccountNumber, Amount AS MyAlias
FROM Transactions
GROUP BY AccountNumber, ISNULL(Amount, 0)
(I.e. SQL Server complains that you haven't included the field Amount in your Group By or aggregate function)
...remember to place the exact same function in your SELECT...
SELECT AccountNumber, ISNULL(Amount, 0) AS MyAlias
FROM Transactions
GROUP BY AccountNumber, ISNULL(Amount, 0)