Turning rows to columns in postgres - sql

I have one table with rental contracts. (Postgres v10.18)
Like this:
Table Rental
Id Start Main_tenant_id Obect_id
101011 1.1.2021 1000 200
100222 1.1.2021 2050 210
If the Object has more than one Tenant the other ones a saved in a separate Table like this:
Table Rental_extra
Id rental_id xtra_tenant
20001 100222 3000
20002 100222 2700
20003 100222 2800
And i have a Person table like this:
Table Person
Id first_name last_name
1000 Peter Mcdonald
2050 Dan Hunt
3000 Steve Cole
2700 Ian Wright
2800 William Pears
Now i need to get this output:
Goal
Id tenant 1 tenant 2 tenant 3 tenant 4
101011 Peter Mcdonald null null null
100222 Dan Hunt Steve Cole Ian Wright William Pears
What's the best way? I tried with some crosstab example but couldn't make it work.

SELECT *
FROM crosstab(
$$
SELECT t.id, tenant_nr, concat_ws(' ', p.first_name, p.last_name)
FROM (
SELECT id, 0 AS tenant_nr, main_tenant_id AS tenant_id
FROM rental
UNION ALL
SELECT rental_id, row_number() OVER (PARTITION BY rental_id ORDER BY id), xtra_tenant
FROM extra_tenant
) t
JOIN person p ON p.id = t.tenant_id
ORDER BY 1 DESC, t.tenant_nr
$$
) AS goal(id int, tenant_1 text, tenant_2 text, tenant_3 text, tenant_4 text);
db<>fiddle here
Detailed explanation here:
PostgreSQL Crosstab Query
Postgres - Transpose Rows to Columns

Related

Dynamic Pivoting in SQL - Snowflake

I have an input file
Customer PhoneNum Location Brand
John 1234 ABC Oppo
John 1234 DEF MI
John 1234 KLM RealMe
John 1234 LKM 1+
Joe 9934 ABC Apple
Joe 9934 DEF Samsung
The same phone number can be listed to multiple phone brands and the number of brands per phone number can be dynamic i.e. some can have 2 brands some can have 4 some 8 etc. I can pass the list of unique brands in the pivot query but that would create columns which might not have values.
the result i want is
Customer PhoneNum Brand1 Brand1Location Brand2 Brand2Location Brand3 Brand3Location Brand4 Brand4Location
John 1234 Oppo ABC MI DEF RealMe KLM 1+ LKM
Joe 9934 Apple ABC Samsung DEF
```
Here i dont need the list of brands but if i know the maximum record per number is say 4 i can have the output in above format, which I believe is a good way to read the result.
Is there any way in SQL to get the above result.
select * from phone_multiple_make
pivot(max(location),max(brand) for brand in
('MI','Oppo','RealMe') )as p;
If you're ok with not using a pivot function you can acheive your results like this:
WITH CTE AS (
SELECT 'John' CUSTOMER,1234 PHONENUM,'ABC' LOCATION,'Oppo' BRAND
UNION
SELECT 'John' CUSTOMER,1234 PHONENUM,'DEF' LOCATION,'MI' BRAND UNION
SELECT 'John' CUSTOMER,1234 PHONENUM,'KLM' LOCATION,'RealMe' BRAND UNION
SELECT 'John' CUSTOMER,1234 PHONENUM,'LKM' LOCATION,'1+' BRAND UNION
SELECT 'Joe' CUSTOMER,9934 PHONENUM,'ABC' LOCATION,'Apple' BRAND UNION
SELECT 'Joe' CUSTOMER,9934 PHONENUM,'DEF' LOCATION,'Samsung' BRAND )
SELECT CUSTOMER, PHONENUM
,J:BRAND1:BRAND::STRING BRAND1, J:BRAND1:LOCATION::STRING LOCATION1
,J:BRAND2:BRAND::STRING BRAND2, J:BRAND2:LOCATION::STRING LOCATION2
,J:BRAND3:BRAND::STRING BRAND3, J:BRAND3:LOCATION::STRING LOCATION3
,J:BRAND4:BRAND::STRING BRAND4, J:BRAND4:LOCATION::STRING LOCATION4
FROM (
SELECT CUSTOMER, PHONENUM, OBJECT_AGG(KEY,OBJ) J FROM (
SELECT CUSTOMER, PHONENUM
,'BRAND'||ROW_NUMBER()OVER(PARTITION BY CUSTOMER,PHONENUM ORDER BY BRAND)::STRING KEY
,OBJECT_CONSTRUCT( 'LOCATION', LOCATION, 'BRAND',BRAND) OBJ FROM CTE) GROUP BY 1,2)

joining 2 tables in sql which has no dependency on each other

I have 2 tables in the following way
Table 1:
e_id e_name e_salary e_age e_gender e_dept
---------------------------------------------------
1 sam 95000 45 male operations
2 bob 80000 21 male support
3 ann 125000 25 female analyst
Table 2:
d_salary d_age d_gender e_dept
----------------------------------
34000 25 male Admin
56000 41 female Tech
77000 35 female HR
I want the output something like this:
e_id e_name e_salary e_age e_gender e_dept d_salary d_age d_gender e_dept
1 sam 95000 45 male operations 34000 25 male Admin
2 bob 80000 21 male support 56000 41 female Tech
3 ann 125000 25 female analysts 77000 35 female HR
There is no dependency between the tables. No common columns. No primary or foreign key.
I tried using cross join that results in duplicate rows because it works on M X N
I am new to this SQL thing. Can someone help me, please? Thanks in advance
Though I didn't get the reason behind your desired output but you can get that with below query:
select a.e_id ,a.e_name ,a.e_salary ,a.e_age ,a.e_gender ,a.e_dept,b.d_salary ,b.d_age ,b.d_gender ,b.e_dept
from
(select e_id ,e_name ,e_salary ,e_age ,e_gender ,e_dept, row_number()over(order by e_id)rn
from table1)a
inner join
(select d_salary d_age d_gender e_dept,row_number()over(order by d_salary) rn
from table 2) b
on a.rn=b.rn
Generally you can create a row count using the row_number() window function on both tables and use this as join criterion. But this requires a certain order for both tables, which means that you have explicitly tell the query why is the Admin record ordered first and must be joined on the first record of table 1:
SELECT
*
FROM (
SELECT
*,
row_number() OVER (ORDER BY e_id) as row_count -- assuming e_id is your order criterion
FROM table1
) t1
JOIN (
SELECT
*,
row_number() OVER (ORDER BY /*whatever you expect to be ordered*/) as row_count
FROM table2
) t2
ON t1.row_count = t2.row_count

Filtering SQL rows based on values from other rows

Using a SQL Server 2016 SP1 database I have this data in table name AgentsTable:
SELECT * FROM AgentsTable;
user_id first_name last_name agent_id agent_status agent_code
2003015038088 John Brown 22307 Retired 12345
2003015038088 John Brown 22307 Death 12399
4432442556456 Mary Jane 24667 Active 32133
7746234737464 Harry Smith 29981 Retired 42354
3455555657677 Mark Aguy 29654 Active 34655
5436546674465 Sally Sam 22584 Retired 45464
The second row shows that 'John Brown' is dead (agent_status = 'Death'), so I would like to exclude all rows for that agent_id who is dead. (Note that John Brown has two different agent_codes, so there's one row for each agent_code. That's how the source data is...)
This query:
SELECT * FROM AgentsTable WHERE agent_status = 'Retired';
Will return this:
user_id first_name last_name agent_id agent_status agent_code
2003015038088 John Brown 22307 Retired 12345
7746234737464 Harry Smith 29981 Retired 42354
5436546674465 Sally Sam 22584 Retired 45464
The result I want, where John Brown (22307) is excluded, is:
user_id first_name last_name agent_id agent_status agent_code
7746234737464 Harry Smith 29981 Retired 42354
5436546674465 Sally Sam 22584 Retired 45464
How can I achieve that? In other words, how can I exclude one row based on a value in another related row?
You can use CTE and get agents who are not deceased as given below:
;WITH CTE_deceasedagents AS
(
SELECT agent_id
FROM AgentsTable
WHERE agent_status = 'Death'
)
SELECT *
FROM AgentsTable as a
WHERE NOT EXISTS
(
SELECT agent_id
FROM CTE_deceasedagents as c
WHERE c.agent_id = a.agent_id
);
GO
SELECT * FROM AgentsTable t1 WHERE agent_status = 'Retired' where NOT EXISTS (SELECT 1 FROM AgentsTable t2 WHERE t2.agent_status = 'Death' and t2.agent_code = t1. agent_code );
I would just use not exists with a correlated subquery to ensure that no other record exists with the same user_id and a 'Death' status:
select a.*
from agentsTable a
where not exists (
select 1
from agentsTable a1
where a1.user_id = a.user_id and a1.agent_status = 'Death'
)

sql that identifies which account numbers have multiple agents

I dont think a count will work here, can someone help me get an sql that identifies which account numbers have multiple agents, more than two agents in the where condition.
AGENT_NAME ACCOUNT_NUMBER
Clemons, Tony 123
Cipollo, Michael 123
Jepsen, Sarah 567
Joanos, James 567
McMahon, Brian 890
Novak, Jason 437
Ralph, Melissa 197
Reitwiesner, John 221
Roman, Marlo 123
Rosenzweig, Marcie 890
Results should be something like this.
ACCOUNT_NUMBER AGENT_NAME
123 Cipollo, Michael
123 Roman, Marlo
123 Clemons, Tony
890 Rosenzweig, Marcie
890 McMahon, Brian
567 Joanos, James
567 Jepsen, Sarah
You can do this using window functions:
select t.account_number, t.agent_name
from (select t.*, min(agent_name) over (partition by account_number) as minan,
max(agent_name) over (partition by account_number) as maxan
from table t
) t
where minan <> maxan;
If you know the agent names are never duplicated, you could just do:
select t.account_number, t.agent_name
from (select t.*, count(*) over (partition by account_number) as cnt
from table t
) t
where cnt > 1;
Assuming your table name is test, this should pull all the records with duplicate ACCOUNT_NUMBER:
select * from test where ACCOUNT_NUMBER in
(select ACCOUNT_NUMBER from test
group by ACCOUNT_NUMBER having
count(ACCOUNT_NUMBER)>1)
order by ACCOUNT_NUMBER
Using count function u can get the result
CREATE TABLE #TEMP
(
AGENT_NAME VARCHAR(100),
ACCOUNT_NUMBER INT
)
INSERT INTO #TEMP
VALUES ('CLEMONS, TONY',123),
('CIPOLLO, MICHAEL',123),
('JEPSEN, SARAH',567),
('JOANOS, JAMES',567),
('MCMAHON, BRIAN',890),
('NOVAK, JASON',437),
('RALPH, MELISSA',197),
('REITWIESNER, JOHN',221),
('ROMAN, MARLO',123),
('ROSENZWEIG, MARCIE',890)
SELECT a.ACCOUNT_NUMBER,a.AGENT_NAME
FROM #TEMP A
JOIN(SELECT COUNT(1) CNT,
ACCOUNT_NUMBER
FROM #TEMP
GROUP BY ACCOUNT_NUMBER) B
ON A.ACCOUNT_NUMBER = B.ACCOUNT_NUMBER
WHERE B.CNT != 1

Select query which returns exect no of rows as compare in values of sub query

I have got a table named student. I have written this query:
select * From student where sname in ('rajesh','rohit','rajesh')
In the above query it's returning me two records; one matching 'rajesh' and another matching: 'rohit'.
But i want there to be 3 records: 2 for 'rajesh' and 1 for 'rohit'.
Please provide me some solution or tell me where i am missing.
NOTE: the count of result of sub query is not fix there can be many words there some distinct and some multiple occurrence .
Thanks
Your requirements are not clear, and I'll try to explain why.
Let's define table students
ID FirstName LastName
1 John Smith
2 Mike Smith
3 Ben Bray
4 John Bray
5 John Smith
6 Bill Lynch
7 Bill Smith
Query with WHERE clause:
FirstName in ('Mike', 'Ben', 'Mike')
will return 2 rows only, because it could be rewritten as:
FirstName='Mike' or FirstName='Ben' or FirstName='Mike'
WHERE is filtering clause that just says if existing row satisfy given conditions or not (for each of rows created by FROM clause.
Let's say we have subquery that returns any number of non distinct FirstNames
In case if SQ contains 'Mike', 'Ben', 'Mike' using inner join you can get those 3 rows without problem
Select ST.* from Students ST
Inner Join (Select name from …. <your subquery>) SQ
On ST.FirstName=SQ.name
Result will be:
ID FirstName LastName
2 Mike Smith
2 Mike Smith
3 Ben Bray
Note data are not ordered by order of names returning by SQ. If you want that, SQ should return some ordering number, eg.:
Ord Name
1. Mike
2. Ben
3. Mike
In that case query should be:
Select ST.* from Students ST
Inner Join (Select ord, name from …. <your subquery>) SQ
On ST.FirstName=SQ.name
Order By SQ.ord
And result:
ID FirstName LastName
2 Mike Smith (1)
3 Ben Bray (2)
2 Mike Smith (3)
Now, let's se what will happen if subquery returns
Ord Name
1. Mike
2. Bill
3. Mike
You will end up with
ID FirstName LastName
2 Mike Smith (1)
6 Bill Lynch (2)
7 Bill Smith (2)
2 Mike Smith (3)
Even worse, if you have something like:
Ord Name
1. John
2. Bill
3. John
Result is:
ID FirstName LastName
1 John Smith (1)
4 John Bray (1)
5 John Smith (1)
6 Bill Lynch (2)
7 Bill Smith (2)
1 John Smith (3)
4 John Bray (3)
5 John Smith (3)
This is an complex situation, and you have to clarify precisely what requirement is.
If you need only one student with the same name, for each of rows in SQ, you can use something like SQL 2005+):
;With st1 as
(
Select Row_Number() over (Partition by SQ.ord Order By ID) as rowNum,
ST.ID,
ST.FirstName,
ST.LastName,
SQ.ord
from Students ST
Inner Join (Select ord, name from …. <your subquery>) SQ
On ST.FirstName=SQ.name
)
Select ID, FirstName, LastName
From st1
Where rowNum=1 -- that was missing row, added later
Order By ord
It will return (for SQ values John, Bill, John)
ID FirstName LastName
1 John Smith (1)
6 Bill Lynch (2)
1 John Smith (3)
Note, numbers (1),(2),(3) are shown to display value of ord although they are not returned by query.
If you can split the where clause in your calling code, you could perform a UNION ALL on each clause.
SELECT * FROM Student WHERE sname = 'rajesh'
UNION ALL SELECT * FROM Student WHERE sname = 'rohit'
UNION ALL SELECT * FROM Student WHERE sname = 'rajesh'
Try using a JOIN:
SELECT ...
FROM Student s
INNER JOIN (
SELECT 'rajesh' AS sname
UNION ALL
SELECT 'rohit'
UNION ALL
SELECT 'rajesh') t ON s.sname = t.sname
just because you've got a criteria in there two times doesn't mean that it will return 1 result per criteria. SQL engines usually just use the unique criteria - thus, from your example, there will be 2 criteria in IN clause: 'rajesh','rohit'
WHY do you need to return 2 results? are there two rajesh in your table? they should BOTH return then. You don't need to ask for rajesh twice for that to happen. What does your data look like? What do you want to see returned?
Hi i am query just as you give above and it give me all data that matches in the condition of in clause. just like your post
select * from person
where personid in (
'Carson','Kim','Carson'
)
order by FirstName
and its give me all records which fulfill this Criteria