SQL Union Select for alternate data - sql

I created an sql query with union select and here is the query to join the two columns into one.
(select top 10 FirstName from Users) union (select top 10 LastName from Users)
Here is the Result:
QUERY RESULT 1
And here is the original data for the result 1 of union select.
ORIGINAL DATA
So, here is my problem.
How do I select the data of each firstname and lastname with the same column but the first one is firstname and the second one is lastname. For example:
Tumbaga Temp - <FirstName>
Villamor - <LastName>
Jun - <FirstName>
Villamor - <LastName>
FN83 - <FirstName>
Lising Geron - <LastName>
So on and so fort.
I am new in sql query. Thanks for your help.

We add a common row_number() to both parts to essentially group them, then order by this and the name type to display in clusters of first/last pairs
select 'First' as thename,
Firstname,
row_number() over(order by firstname) rn
from Users
union all
select 'Last',
Lastname,
row_number() over(order by firstname)
from users
order by rn, thename
If you only want the 1st 10, then wrap this and add a clause
select *
from
(
select 'First' as thename,
Firstname,
row_number() over(order by firstname) rn
from Users
union all
select 'Last',
Lastname,
row_number() over(order by firstname)
from users
)
where rn <=10
order by rn, thename

No need to use union, As per your description You have two columns 'firstName' and 'lastName' in a table and you want both in a single column. Just try the following query-:
select FirstName+' '+LastName as FullName from Users
SQL Server

you can add a column to both queries with your favourite data to be selected.
(select top 10 FirstName, 'FirstName' as NameType from SysUser) union (select top 10 LastName, 'LastName' as NameType from SysUser)

Related

SQL ignore one field with DISTINCT but ORDER BY it

I have two SQL SELECT with UNION DISTINCT, one with data from a new Database and one from an old Database so in each SELECT I have a field that describes from which Database the data came.
A simplified Example code:
SELECT username, name, lastname, 1 AS DB
From new_DB.users
UNION DISTINCT
SELECT username, name, lastname, 2 AS DB
From old_DB.users
ORDER BY db, lastname, name ASC
Data output looks like this:
username
name
lastname
DB
Fmuster
Fiona
Muster
1
kroos
Kim
Roos
1
Mmuster
Max
Muster
1
kroos
Kim
Roos
2
Ysoroli
Yelda
Soroli
2
My problem is:
That there is duplicated data in the output.
The data that shouldn't be in the output is the second kroos but I can't just remove the field DB because I have to show all results from new_DB(DB 1) at the top.
thx for your help
Kim
You can use NOT EXISTS to filter out duplicate rows coming from old_DB.users:
SELECT username, name, lastname, 1 AS DB
FROM new_DB.users
UNION
SELECT o.username, o.name, o.lastname, 2 AS DB
FROM old_DB.users o
WHERE NOT EXISTS (
SELECT 1
FROM new_DB.users n
WHERE (n.username, n.name, n.lastname) = (o.username, o.name, o.lastname)
)
ORDER BY db, lastname, name ASC;
Or, with aggregation:
SELECT username, name, lastname, MIN(DB) AS DB
FROM (
SELECT username, name, lastname, 1 AS DB
FROM new_DB.users
UNION
SELECT username, name, lastname, 2 AS DB
FROM old_DB.users
) t
GROUP BY username, name, lastname
ORDER BY db, lastname, name ASC;

How to transform Access data similar to crosstab

I have data that I want to display similar to a cross-tab query but not quite. The data I have looks like this with each segment of data on a different row:
I want the data to be consolidated to be all on one row for each client, like this:
I've attempted this with a cross-tab query but I'm not wanting to total any of the fields and there are several data point for each product (Type, Name, PurchaseDate, etc).
Any help is greatly appreciated!
Not a very practical presentation of data but it is possible. Need a unique identifier field - autonumber should serve - I called it RID. Consider:
Query 1:
SELECT RID, ID, FirstName, LastName, Dept, ProductType AS Data, "PT" AS Cat FROM Table1
UNION SELECT RID, ID, FirstName, LastName, Dept, ProductName, "PN" FROM Table1
UNION SELECT RID, ID, FirstName, LastName, Dept, PurchaseDate, "PD" FROM Table1
UNION SELECT RID, ID, FirstName, LastName, Dept, PurchaseCost, "PC" FROM Table1
UNION SELECT RID, ID, FirstName, LastName, Dept, DeliveryDate, "DD" FROM Table1;
Query 2:
TRANSFORM First(Query1.Data) AS FirstOfData
SELECT Query1.ID, Query1.FirstName, Query1.LastName, Query1.Dept
FROM Query1
GROUP BY Query1.ID, Query1.FirstName, Query1.LastName, Query1.Dept
PIVOT DCount("*","Query1","ID=" & [ID] & " AND Cat='" & [Cat] & "' AND RID<" & [RID])+1 & [Cat];
However, there is a limit of 255 fields so there may be more data than can be handled.

List All Rows Containing Duplicates SQL

I want to List All Rows Containing Duplicates by a name in the table for instance, name = TestName or TestName1 or Test name 2..
but also want to know what else is attached to them..
I have done this query.
select firstname,lastname from table
group by firstname,lastname
having count(*) > 1
I have found duplicated records but you're interested in getting all the information attached to them, however this is all on one table..
I have tried to do this..
select * from my_table a join ( select firstname, lastname from my_table group by firstname, lastname having count(*) > 1 ) b on a.firstname = b.firstname and a.lastname = b.lastname
but this is if the data was on 2 separate tables?
You can use window functions:
select t.*
from (select t.*, count(*) over (partition by firstname, lastname) as cnt
from table t
) t
where cnt > 1

SQL Select column which is not used in select section of subquery which find duplicates

I am trying to find in my database records which has duplicated fields like name, surname and type.
Example:
SELECT name, surname, type, COUNT(*)
FROM customers
GROUP BY name, surname
HAVING COUNT(*)>1
Query results:
Robb|Stark|1|2
Tyrion|Lannister|1|3
So we have duplicated customer with name and surname "Robb Stark" 2 times and "Tyrion Lannister" 3 times
Now, I want to know the id of these records.
I found similar problem described here:
Finding duplicate values in a SQL table
there is answer but no example.
Use COUNT as an analytic function:
WITH cte AS (
SELECT *, COUNT(*) OVER (PARTITION BY name, surname) cnt
FROM customers
)
SELECT * -- return all columns
FROM cte
WHERE cnt > 1
ORDER BY name, surname;
The simplest way will be to use the EXISTS as follows:
SELECT t.*
FROM customers t
where exists
(select 1 from customers tt
where tt.name = t.name
and tt.surname = t.surname
and tt.id <> t.id)
Or use your original query in IN clause as follows:
select * from customers where (name, surname) in
(SELECT name, surname
FROM customers
GROUP BY name, surname
HAVING COUNT(*)>1)
If you want one row per group of duplicate, with the list of id in a comma separated string, you can just use string aggration with your existing query:
SELECT name, surname, COUNT(*) as cnt,
STRING_AGG(id, ',') WITHIN GROUP (ORDER BY id) as all_ids
FROM customers
GROUP BY name, surname
HAVING COUNT(*) > 1

How we can use CTE in subquery in sql server?

How we can use a CTE in a subquery in SQL Server?
like:
SELECT id (I want to use CTE here), name FROM table_name
Just define your CTE on top and access it in the subquery?
WITH YourCTE(blubb) AS
(
SELECT 'Blubb'
)
SELECT id,
(SELECT blubb FROM YourCTE),
name
FROM table_name
It doesn't work:
select id (I want to use CTE here), name from table_name
It's not possible to use CTE in sub queries.
You can realize it as a work around:
CREATE VIEW MyCTEView AS ..here comes your CTE-Statement.
Then you are able to do this:
select id (select id from MyCTEView), name from table_name
Create a view with CTE/ Multiple CTEs with UNION sets of all CTEs
CREATE VIEW [dbo].[_vEmployees]
AS
WITH
TEST_CTE(EmployeeID, FirstName, LastName, City, Country)
AS (
SELECT EmployeeID, FirstName, LastName, City, Country FROM Employees WHERE EmployeeID = 4
),
TEST_CTE2
AS (
SELECT EmployeeID, FirstName, LastName, City, Country FROM Employees WHERE EmployeeID = 7
)
SELECT EmployeeID, FirstName, LastName, City, Country FROM TEST_CTE UNION SELECT * FROM TEST_CTE2
GO
Now, use it into sub query
SELECT * FROM Employees WHERE EmployeeID IN (SELECT EmployeeID FROM _vEmployees)