Display SQL results in rows instead of a single line - sql

I have the following tables:
Table Offices:
OfficeID MainAddId SubAddId1 SubAddId2 PortAddId1
------- -------- -------- -------- --------
2 1 2 3 5
Table Address:
AddressID Street City ZipCode State
------- -------- -------- -------- --------
1 Forest Ave New York 10001 New York
2 Morris St Philadelphia 19019 Pennsylvania
3 David St Raleigh 27513 North Carolina
Table Port:
PortID PortName Street City ZipCode State
------- ------- -------- -------- -------- --------
5 New York Harbour Bay St New York 10001 New York
I want to write an SQL request such that if any of the addresses Id in the office table is not null,
it will return the list of addresses in a list like:
AddressID Street City ZipCode State
------- -------- -------- -------- --------
1 Forest Ave New York 10001 New York
2 Morris St Philadelphia 19019 Pennsylvania
3 David St Raleigh 27513 North Carolina
5 Bay St New York 10001 New York
Any help on how I can do this please? Thanks
Here is what I tried (partly cause it's not working):
select *
from Office offi
left join Address add1 on offi.MainAddId = add1.AddressID
left join Address add2 on offi.SubAddId1= add2.AddressID
where offi.OfficeID = 2;
However, this is returning the addresses on a single line.

Don't use multiple joins if you really need them. Instead of that, you can use OR after ON in join.
I solved using UNION:
select a.AddressID, a.street, a.city, a.zipcode, a.state
from offices o
inner join address a on (o.MainAddid = a.addressId or o.subaddid1 = a.addressid or o.subaddid2 = a.addressid)
union
select p.PortId, p.street, p.city, p.zipcode, p.state
from offices o
inner join port p on p.portId = o.PortAddId1
Check demo on DB<>FIDDLE

Try this one query :
SELECT *
FROM ( SELECT AddressID, Street, City, ZipCode, State
FROM address
UNION
SELECT PortID, Street, City, ZipCode, State
FROM Port) w
WHERE addressid IN ( SELECT Addresses
FROM ( SELECT OfficeID, MainAddId, SubAddId1, SubAddId2, PortAddId1
FROM Offices) p
UNPIVOT ( Addresses
FOR Offices IN (MainAddId, SubAddId1, SubAddId2, PortAddId1)) AS unpvt );

Related

Summary by state/county total line or running line

In this Query, I would like to show the total of clients by state/county. Is this possible?
I guess a running total is ok in new column or if possible a break when the state/county changes to show the total of the previous count?
So output like this>
|first_name|last_name|description|description|
VIN ULTI New York Bronx 1
MEL MORRIS New York Bronx 2
BYRAM BROWN New York Bronx 3 or preferred a line total:
*** Total Clients Bronx New York = 3
SELMA MADDISON New York Queens 1
*** Total Clients New York Queens = 1
select ac.first_name, ac.last_name, st.description, co.description
from address ad
inner join all_clients_view ac
on ad.people_id = ac.people_id
inner join county co
on ad.county = co.county_id
inner join state st
on co.state_id = st.state_id
where ad.is_active = 1
order by st.description, co.description
You can try with these scripts:
1) Total of the previuos count:
select ac.first_name, ac.last_name, st.description, co.description,
(select count(*)
from address ad2
inner join all_clients_view ac2
on ad2.people_id = ac2.people_id
inner join county co2
on ad2.county = co2.county_id
inner join state st2
on co2.state_id = st2.state_id
where ad2.is_active = 1
and ad2.county = ad.county
and ad2.people_id <= ad.people_id)
as count_progress
from address ad
inner join all_clients_view ac
on ad.people_id = ac.people_id
inner join county co
on ad.county = co.county_id
inner join state st
on co.state_id = st.state_id
where ad.is_active = 1
order by st.description, co.description, ad.people_id;
FIRST LAST_NAM DESCRIPT DESCRI COUNT_PROGRESS
----- -------- -------- ------ --------------
VIN ULTI New York Bronx 1
MEL MORRIS New York Bronx 2
BYRAM BROWN New York Bronx 3
SELMA MADDISON New York Queens 1
2) Line Total:
select st.description as state, co.description as county, count(*)
from address ad
inner join all_clients_view ac
on ad.people_id = ac.people_id
inner join county co
on ad.county = co.county_id
inner join state st
on co.state_id = st.state_id
where ad.is_active = 1
group by st.description, co.description
order by st.description, co.description;
STATE COUNTY COUNT(*)
-------- ------ ----------
New York Bronx 3
New York Queens 1
Thank you.

two same rows but one column with distinct value, how to combine them and get rid of another line

enter image description hereI have two rows exactly same value except one column, I want to combine them and add another value into new column
Name Address City State ID ID Type
XYZ 123 address New York NY 123 Code1
XYZ 123 address New York NY D561 Code2
ABC 895 address Richmond VA 568A Code1
XAB 456 address Dallas TX 568 Code2
XAB 456 address Dallas TX 458A562 Code1
XYZ 123 address New York NY 123T Code3
Result
Name Address City State Code1 Code2 code3
XYZ 123 Address New York NY 123 D561 123T
ABC 895 address Richmond VA 568A
XAB 456 address Dallas TX 458A562 563
enter image description here
The below query will give you the correct desired o/p as per above input sample or else for a standard you can use PIVOT keyword to have a new column
SELECT Name, Address,City, State,
min(ID) AS ID1,max(ID) AS ID2
FROM your_table
GROUP BY Name, Address,City, State
You can use aggregation:
select Name, Addresss, City, State,
min(id) as id1,
(case when min(id) <> max(id) then max(id) end) as id2
from t
group by Name, Addresss, City, State ;

Check for an entry in SQL Server

-----------------------
country | city | ids
-----------------------
India Mumbai 1
India Chennai 2
India Kolkata 3
---------------------
USA New York 2
USA Utah 3
---------------------
I have given a sample from a table. From the table, I am trying to query all the countries without id 1. I wrote this(Country was not included in the Where condition since it needs to apply to all the countries of the table).
Select * from Countries
WHERE id<>1
I got this.
-----------------------
country | city | ids
-----------------------
India Chennai 2
India Kolkata 3
---------------------
USA New York 2
USA Utah 3
---------------------
But I need the output to contain only USA(which does not have id=1). Is there any workaround for this?
SELECT * from Countries WHERE country not in
(SELECT country from Countries WHERE id=1)
use NOT EXISTS
Select *
from Countries c
where not exists
(
select *
from Countries x
where x.country = c.country
and x.id = 1
)
You need to group by Country like below :
SELECT C.Country
FROM City
WHERE C.Country NOT IN
(SELECT country FROM City WHERE id=1)
SQL Fiddle Demo
OR
SELECT
C.Country
FROM
City C
GROUP BY C.Country
HAVING C.Country NOT IN
(
SELECT Country FROM City WHERE Id =1
)
SQL Fiddle Demo

Concatenating and Pattern Matching SQL

I have 3 tables as follows in SQL:
Accounts, containing
id zip city
---- ----- ---------------
121 20085 Los Angeles
Customer, containing
user id zip
------- ------
121 20085
Addr, containing
zip city-state
----- ----------------
121 Los Angeles, CA
I want to add an extra column in Accounts called location which will be a concatenated field that will take city from Accounts concatenate it with city-state from Addr by matching the city.
I cannot do the regular join as all the zip in Accounts are not there in Addr so I will loose many records, but the table Customer contains all the zip and user id so I think I can make use of that.
The output desired:
Accounts, containing
user id zip city location
------- ----- ---------------- ----------------
121 20085 Los Angeles Los Angeles;Los Angeles, CA
Are you after something like this:
SELECT
`c`.`user_id`,
`c`.`zip`,
`a`.`city`,
CONCAT_WS( ';', `c`.`city`, `aa`.`city-state` ) AS `location`
FROM
`Accounts` AS `a`
LEFT JOIN
`Addr` AS `aa`
ON
`aa`.`zip`, `a`.`id`
LEFT JOIN
`Customer` AS `c`
ON
`c`.`user id`, `a`.`id`

SQL Pivot with String

I have two tables in SQL Server: Customer and Address
Customer Table:
CustomerID FirstName LastName
----------- ---------- ----------
1 Andrew Jackson
2 George Washington
Address Table:
AddressID CustomerID AddressType City
----------- ----------- ----------- ----------
1 1 Home Waxhaw
2 1 Office Nashville
3 2 Home Philadelphia
This is the output that I need:
CustomerID Firstname HomeCity OfficeCity
----------- ---------- ---------- ----------
1 Andrew Waxhaw Nashville
2 George Philadelphia Null
This is my query, but not getting the right result:
SELECT CustomerID, Firstname, HOme as HomeCity, Office as OfficeCity FROM
(SELECT C.CustomerID, C.FirstName, A.AddressID, A.AddressType, A.City
FROM Customer C, Address A
WHERE C.CustomerID = A.CustomerID)as P
PIVOT (MAX(city) FOR AddressType in ([Home],[Office])) as PVT
This is the result that I am getting:
CustomerID Firstname HomeCity OfficeCity
----------- ---------- ---------- ----------
1 Andrew Waxhaw NULL
1 Andrew NULL Nashville
2 George Philadelphia Null
As you can see Customer 1 is showing up twice in the final result. Is it possible to get only one row per customer?
I looked up this example, but didn't help:http://stackoverflow.com/questions/6267660/sql-query-to-convert-rows-into-columns
Thanks
It is giving this row because you have AddressID in the select list for you subquery "P". So even though you don't have AddressID in you top level select this, the PIVOT function is still grouping by it. You need to change this to:
SELECT CustomerID, Firstname, Home as HomeCity, Office as OfficeCity
FROM ( SELECT C.CustomerID, C.FirstName, A.AddressType, A.City
FROM #Customer C, #Address A
WHERE C.CustomerID = A.CustomerID
) AS P
PIVOT
( MAX(city)
FOR AddressType in ([Home],[Office])
) AS PVT
Although I would be inclined to use an explicit INNER JOIN rather than an implicit join between customer and Address.
I would write it like this instead:
SELECT C.CustomerID, C.Firstname,
Home.City as HomeCity,
Office.City as OfficeCity
FROM Customer C
LEFT JOIN Address Home
on Home.CustomerID = C.CustomerID and Home.AddressType = 'Home'
LEFT JOIN Address Office
on Office.CustomerID = C.CustomerID and Office.AddressType = 'Office'