How to join two SQL queries? - sql

Making two SQL queries into the same table
SELECT FirstName,
LastName,
LEFT(FirstName, 1) + '.' + LEFT(LastName, 1) AS Initial
FROM ContactUpdates
This outputs:
FirstName LastName Initial
I want this to join this other one on the right side where Initial ends
SELECT LOWER(LEFT(FirstName, 1) + REPLACE(LastName,'''','' ) )
+ '#email.com' AS Email
FROM ContactUpdates
In the end I want it to be
FirstName LastName Initial Email
But I can't figure out how to make them join any help?

SELECT FirstName,
LastName,
LEFT(FirstName,1) + '.' + LEFT(LastName,1) AS Initial,
LOWER(LEFT(FirstName, 1) + REPLACE(LastName, '''', '')) + '#email.com' AS Email
FROM ContactUpdates

Then simply append that column to the query:
SELECT FirstName
, LastName
, LEFT(FirstName,1) + '.' + LEFT(LastName,1) AS Initial
, LOWER(LEFT(FirstName,1) + REPLACE(LastName,'''','' ) ) + '#email.com' AS Email
FROM ContactUpdates

Related

Manipulating duplicate values?

I have a table, with an ID, FirstName & Lastname.
I'm selecting that using the following query:
SELECT USER_ID as [ID], First_P + ' ' + Last_P as FullName FROM Persons
It's working fine. I'm basically having a list of ID's and full names.
Full names could be the same. How is it possible for me to find them and add the ID on the Full name cell as well? only when the names are the same.
Example:
1 John Wick (1)
50 John Wick (50)
I haven't found any similar questions to be honest, at least not for MSSQL. So If there are any, feel free to link me.
please take a look my answer. I used nested query to identify number of duplicated names
SELECT
ID,
IIF(NUMBEROFDUPS =1, NAME, CONCAT(NAME, ' (', ID, ')')) AS NAME
FROM
(
SELECT
ID,
CONCAT(First_P, ' ', Last_P) AS NAME,
COUNT(*) OVER (PARTITION BY First_P,Last_P) AS NUMBEROFDUPS
FROM
Table1
) tmp;
You can use outer apply to group the items via First_P + ' ' + Last_P
and then add case for multiple items.
The select stuff should look like:
SELECT USER_ID as [ID], p1.First_P + ' ' + p1.Last_P + case when cnt.FullName is not null
then '(' + p2.[sum] + ')' else '' end as FullName FROM Persons p1
outer apply (select First_P + ' ' + Last_P as FullName,count(1) as [sum]
from Persons p2
where p2.First_P + ' ' + p2.Last_P = p1.First_P + ' ' + p1.Last_P
group by First_P + ' ' + Last_P
having count(1) > 1) cnt

How can I store a SELECT query result(one column) into a new table's column?

This is my query:-
select
(FirstName + ' ' + Lastname) as [Name]
from
c_client
where
MiddleInitial is null
union
select
(FirstName + ' ' + MiddleInitial + '''' + Lastname) as [Name]
from
c_client
where
MiddleInitial is not null
After executing it, I'm getting this output:
This is my new table:
CREATE TABLE AddData(Name VARCHAR(MAX))
I want to insert the result generated by the SELECT query into my new table AddData. Can you help me do this?
You would use insert:
insert into AddData (Name)
Select (FirstName + ' ' + Lastname) as [Name]
from c_client
where MiddleInitial IS NULL
UNION
Select (FirstName + ' ' + MiddleInitial +''''+ Lastname) as [Name]
from c_client
where MiddleInitial IS NOT NULL;
I would instead suggest writing the logic as :
select (FirstName +
coalesce(MiddleInitial + '''', '') +
' ' +
Lastname
) as Name
into AddData
from c_client c;
You won't have to create the table first.
Also, if you do want to remove duplicates then use select distinct. It is not clear if you are using union intentionally to remove duplicates or just to combine two separate subqueries.

column values into one string in sql stored procedure

I have and address table with the following columns:
addressId
buildingName
streetNo
streetName
streetType
subAddressNo
subAddressType
suburb
postCode
state
What I want is to SELECT * from address where addressId = #addressId, and that return would be all columns concatenated into one string. Something like:
set #addressString = (SELECT * from address where addressId = #addressId)
select coalesce(cast(addressId as varchar)+ ',', '') + coalesce(buildingName+ ',', '')
coalesce(cast(streetNo as varchar)+ ',', '') -- + and so on
from address
remember to cast the numeric types as varchar
Try this:
SELECT buldingName + ' ' + streetNo + ' ' + streetName + ' ' + theRestOfYourColumns AS ClientAddress
FROM YourAddressTable
WHERE addressId = #addressIdPreviouslyAssignedVariable

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)