Combining 2 coloumns into 1 - sql-server

Find the customer number, last name, and first name. Display the name as one column titled "Name"
SELECT A.CustomerNumber (A.LName B.FName) AS Name
FROM Customers as A
LEFT JOIN Customers as B
ON A.CustomerNumber=B.CustomerNumber;
What can I use to do this properly

Shouldn't it be as simple as this?
I cannot see any value in your attempt to join a row with the same row of the same table...
SELECT CustomerNumber
,LName + ' ' + FName AS Name
FROM Customers;
Attention: Make sure, that both name parts are not NULL, otherwise the whole concatenated string will be NULL...

You can use the CONCAT-function, like this:
SELECT A.CustomerNumber, CONCAT(A.LName, ' ', B.FName) AS Name
FROM Customers as A
LEFT JOIN Customers as B
ON A.CustomerNumber=B.CustomerNumber;

Related

Merge multiple rows into a column while replacing the keys with a 'name' field from the original table

I've got a join table that has 'account_id' and 'group id' in it, both represented by a GUID. I'm trying to merge the columns so we get a single 'account_id' with all of it's 'group_id's merged to a single Colum/row, but display the actual name of the account and group.
Tables
Account
account_id Name
1 Henry
2 Smith
Group
Group_id Group_nameName
3 User
4 Admin
Account_Group_Join_Table
account_id group_id
1 3
1 4
2 3
Desired Result:
Name Groups
Henry Dev,User
Smith User, Admin
Code so far to return 'account_id' with 'group_id' grouped to single row/column
select account_id,
stuff((SELECT distinct ', ' + group_id
FROM account_group_join t2
where t2.account_id = t1.account_id
FOR XML PATH('')),1,1,'') [Groups]
from account_group_join t1
group by account_id
You just need to join to your group table in the subquery so you can get the name rather than the ID. You also may as well just select from Account in the outer query and avoid an additional join to account to get the name:
SELECT a.account_id,
a.Name,
STUFF((SELECT DISTINCT ', ' + g.group_nameName
FROM account_group_join AS ag
INNER JOIN [Group] AS g
ON g.group_id = ag.group_id
WHERE ag.account_id = a.account_id
FOR XML PATH('')),1,1,'') AS [Groups]
from Account AS a;
n.b. I've changed your aliases from t1 and t2 to something that kind of represents the table I am aliasing, you'll find this much easier especially when working with larger queries. More reading here: Bad Habits to Kick : Using table aliases like (a, b, c) or (t1, t2, t3)

How do I generate Unique Username using TSQL?

I am trying to generate unique Login username for each users in my system.
What I have done so far is:
Select p.FirstName+P.LastName + p.PersonId from person As P
Here 1255 is Primary Key. The Output is like JamesHarley1255 ,
However I don't want to use the Primarykey. What are other
alternatives.There will be numerous Duplicate Records too.
Lets say I need a function that generates a unique number everytime between 1 to n numbers. And somehow I need to produce output like JamesHarley125
Try this,
Select p.FirstName+P.LastName +CAST(ROW_NUMBER() OVER (ORDER BY p.FirstName) AS VARCHAR(20))
from person As P
If you want to get one unique column against each record without using primary key column, I think you can use Row Number function. Query below should work in this case
Select p.FirstName+P.LastName + CAST((row_number() OVER ( PARTITION BY p.FirstName ORDER BY p.FirstName)) AS varchar(100)) from person As P
You can create an column with incremental integers using identity property and you can concatenate the same with the first name and last name. So that each row will be unique.
Select p.FirstName+P.LastName + P.Id from person As P
Here column P.Id can declared as below in the table definition. This will start with value '1' and will be incremented in the scale of '1'. Identity(seed, increment)
id int IDENTITY(1,1)
Building off the previous responses, this generates usernames without the numbers where possible, and then only adds numbers to make the usernames unique where actually required. I know this isn't the exact way you are generating your usernames, but this is how I decided to generate mine. I just changed the table names to match yours.
with Usernames(PersonId, Username) as
(
select PersonId,
left(Firstname, 1) + Middlename + Lastname as Username
from Person
),
NumberedUserNames(PersonId, Username, Number) as
(
select PersonId,
Username,
ROW_NUMBER() OVER (PARTITION BY Username ORDER BY Username) as Number
from Usernames
),
UniqueUsernames(PersonId, UniqueUsername) AS
(
select PersonId,
case when Number = 1 then UserName
else UserName + CAST(Number-1 as VarChar(20))
End as UniqueUsername
from NumberedUserNames
)
select PersonId,
UniqueUsername
from UniqueUsernames;

Need help MSSQL query to bring table with two columns into one showing unique value of field 1 and corresponding values in field 2 (in that order)?

Picture of current state and desired state
Need help MSSQL query to bring table with two columns into one showing unique value of field 1 and corresponding values in field 2 (in that order)? See picture attached in link above
Your request sounds quite strange, but if you want to do it, one way is to use rollup + grouping_id like this:
select case when grouping_id(field2) = 1 then field1 else field2 end
from yourtable
group by field1, rollup(field2)
order by field1, grouping_id(field2) desc, field2
Usually you'd use this for subtotals, but using it with case you can add additional rows to the data.
This will return:
x
a
b
c
d
y
e
f
g
z
h
i
Edit: How to list table + column names:
select case when grouping_id(c.name) = 1 then t.name else c.name end
from sys.tables t join sys.columns c on t.object_id = c.object_id
group by t.name, rollup(c.name)
order by t.name,c.name

Counting an object depends on a column instead of table SQL

Is there a way to help me on counting the chair that had appear on Monday,Tuesday, and Wednesday instead of the number of the chairs appear in the table?
I expect to get the count of the chair depends on the Order Column instead of the whole table, so the answer will be 3(the chair had appear in monday,tuesday and wednesday) instead of the total number of the chair had appear in the table
use count (distinct column name)
SELECT COUNT ( DISTINCT Order )
FROM yourtable
WHERE Stuff = 'Chair'
EDIT :
I have another question, can it show which Order it has been appear?
like the out put is 3 times follow by (Monday,Tuesday,Wednesday) , is
it possible to show the Order follow by the total count number? or in
other line
is this what you wanted ?
SELECT Order, COUNT (*)
FROM yourtable
WHERE Stuff = 'Chair'
GROUP BY Order
or perhaps this ?
SELECT COUNT ( DISTINCT Order ),
STUFF ((SELECT ',' + Order
FROM yourtable
WHERE Stuff = 'Chair'
GROUP BY Order
FOR XML PATH ('')),
1, 1, '')
FROM yourtable
WHERE Stuff = 'Chair'

Joining a table based on comma separated values

How can I join two tables, where one of the tables has multiple comma separated values in one column that reference an id in another column?
1st table
Name | Course Id
====================
Zishan | 1,2,3
Ellen | 2,3,4
2nd table
course id | course name
=======================
1 | java
2 | C++
3 | oracle
4 | dot net
Maybe this uglyness, I have not checked results:
select names.name, courses.course_name
from names inner join courses
on ',' + names.course_ids + ',' like '%,' + cast(courses.course_id as nvarchar(20)) + ',%'
First of all your Database structure is not normalized and should have been. Since it is already set up this way , here's how to solve the issue.
You'll need a function to split your string first:
CREATE FUNCTION SPLIT_STRING(str VARCHAR(255), delim VARCHAR(12), pos INT) RETURNS VARCHAR(255)
RETURN REPLACE(SUBSTRING(SUBSTRING_INDEX(str, delim, pos),
LENGTH(SUBSTRING_INDEX(str, delim, pos-1)) + 1), delim, '');
Then you'll need to create a view in order to make up for your structure:
CREATE VIEW database.viewname AS
SELECT SPLIT_STRING(CourseID, ',', n) as firstField,
SPLIT_STRING(CourseID, ',', n) as secondField,
SPLIT_STRING(CourseID, ',',n) as thirdField
FROM 1stTable;
Where n is the nth item in your list.
Now that you have a view which generates your separated fields, you can make a normal join on your view, just use your view like you would use a table.
SELECT *
FROM yourView
JOIN table1.field ON table2.field
However since I don't think you'll always have 3 values in your second field from your first table you'll need to tweak it a little more.
Inspiration of my answer from:
SQL query to split column data into rows
and
Equivalent of explode() to work with strings in MySQL
SELECT f.name,s.course_name FROM table1 AS f
INNER JOIN table2 as s ON f.course_id IN (s.course_id)
Use the Below Query For Solution
Select * from table_2 t2 INNER JOIN table_1 t1 on t1.Course Id = t2.course id

Resources