PostgreSQL how to use count with boolean true value only - postgresql

I'm trying to get 2 columns. One with only true values of patient_healty and second with all values of patient_healty from department.
select
count(p1.patient_health) as not_health,
count(patient.id) as all,
department.name
from
department
inner join
doctor on department.id = doctor.department_id
inner join
healing on doctor.id = healing.doctor_id
inner join
patient as p1 on healing.patient_id = p1.id
inner join
patient on healing.patient_id = patient.id
group by
department.name
This will return two columns of all values from patient_health and name of the department. Thanks

If I understand correctly, you can use avg():
select avg(p1.patient_health::int)

Related

Selecting single rows that have max value for each unique name in different column

I need to find a unique set of province, district (accordingly 'wojewodztwo', 'powiat')
for max value in column called 'liczba'
So basically i need to find district with the biggest value for each unique province
My data base looks like this
And I used this command
select
wojewodztwo,
powiat,
count(typmsc) as liczba
from
wojewodztwa
inner join powiaty
on wojewodztwa.klwoj = powiaty.klwoj
inner join gminy
on powiaty.klpow = gminy.klpow
inner join miejscowosci
on gminy.klgm = miejscowosci.klgm
inner join typymsc
on miejscowosci.kltm = typymsc.kltm
where
typmsc = 'miasto'
group by
wojewodztwo,
powiat
To obtain table that looks like this
I tried to obtain the result by using this query above and making it a temporary (temp) table so i can work on it that way but i couldn't come up with a solution
I want my result to look something like this
The result should have 16 rows of each unique province name (thats how many provinces my country have)
I managed to do it
I used this query
select distinct on(wojewodztwo) wojewodztwo, powiat, liczba from(
select wojewodztwo, powiat, count(typmsc) as liczba from wojewodztwa
inner join powiaty on wojewodztwa.klwoj = powiaty.klwoj
inner join gminy on powiaty.klpow = gminy.klpow
inner join miejscowosci on gminy.klgm = miejscowosci.klgm
inner join typymsc on miejscowosci.kltm = typymsc.kltm
where typmsc = 'miasto'
group by wojewodztwo,powiat
) as temp
order by wojewodztwo,liczba desc
And here is the output i got

How to find in a many to many relation all the identical values in a column and join the table with other three tables?

I have a many to many relation with three columns, (owner_id,property_id,ownership_perc) and for this table applies (many owners have many properties).
So I would like to find all the owner_id who has many properties (property_id) and connect them with other three tables (Table 1,3,4) in order to get further information for the requested result.
All the tables that I'm using are
Table 1: owner (id_owner,name)
Table 2: owner_property (owner_id,property_id,ownership_perc)
Table 3: property(id_property,building_id)
Table 4: building(id_building,address,region)
So, when I'm trying it like this, the query runs but it returns empty.
SELECT address,region,name
FROM owner_property
JOIN property ON owner_property.property_id = property.id_property
JOIN owner ON owner.id_owner = owner_property.owner_id
JOIN building ON property.building_id=building.id_building
GROUP BY owner_id,address,region,name
HAVING count(owner_id) > 1
ORDER BY owner_id;
Only when I'm trying the code below, it returns the owner_id who has many properties (see image below) but without joining it with the other three tables:
SELECT a.*
FROM owner_property a
JOIN (SELECT owner_id, COUNT(owner_id)
FROM owner_property
GROUP BY owner_id
HAVING COUNT(owner_id)>1) b
ON a.owner_id = b.owner_id
ORDER BY a.owner_id,property_id ASC;
So, is there any suggestion on what I'm doing wrong when I'm joining the tables? Thank you!
This query:
SELECT owner_id
FROM owner_property
GROUP BY owner_id
HAVING COUNT(property_id) > 1
returns all the owner_ids with more than 1 property_ids.
If there is a case of duplicates in the combination of owner_id and property_id then instead of COUNT(property_id) use COUNT(DISTINCT property_id) in the HAVING clause.
So join it to the other tables:
SELECT b.address, b.region, o.name
FROM (
SELECT owner_id
FROM owner_property
GROUP BY owner_id
HAVING COUNT(property_id) > 1
) t
INNER JOIN owner_property op ON op.owner_id = t.owner_id
INNER JOIN property p ON op.property_id = p.id_property
INNER JOIN owner o ON o.id_owner = op.owner_id
INNER JOIN building b ON p.building_id = b.id_building
ORDER BY op.owner_id, op.property_id ASC;
Always qualify the column names with the table name/alias.
You can try to use a correlated subquery that counts the ownerships with EXISTS in the WHERE clause.
SELECT b1.address,
b1.region,
o1.name
FROM owner_property op1
INNER JOIN owner o1
ON o1.id_owner = op1.owner_id
INNER JOIN property p1
ON p1.id_property = op1.property_id
INNER JOIN building b1
ON b1.id_building = p1.building_id
WHERE EXISTS (SELECT ''
FROM owner_property op2
WHERE op2.owner_id = op1.owner_id
HAVING count(*) > 1);

LEFT OUTER JOIN IN ENTITY FRAMEWORK

I am trying left outer join entity framework by joining 4 tables:
var ssss = (from supplier in entity.Supplier_master
join city in entity.City_master on supplier.Supplier_City equals city.id
join state in entity.State_master on supplier.Supplier_State equals state.id
join country in entity.Country_master on supplier.Supplier_Country equals country.id
where supplier.Supplier_Code.Equals(sup_code)
select (new { supplier.Supplier_Code, supplier.Supplier_Name, city.City_Name, state.State_Name, country.Country_Name, supplier.Supplier_TradeMark })).ToList();
The above code is executed as inner join, please help me to find the solution to done left outer join.
Join the 2 table usering "into alias" then select from that result.
Example:
var query = from supplier in entity.Supplier_master
join city in entity.City_master on supplier.Supplier_City equals city.id into citySupplier
from cs in citySupplier.DefaultIfEmpty()
select new { your fields) };

Get Greatest date across multiple columns with entity framework

I have three entities: Group, Activity, and Comment. Each entity is represented in the db as a table. A Group has many Activities, and an Activity has many comments. Each entity has a CreatedDate field. I need to query for all groups + the CreatedDate of the most recent entity created on that Group's object graph.
I've constructed a sql query that gives me what I need, but I'm not sure how to do this in entity framework. Specifically this line: (SELECT MAX(X)
FROM (VALUES (g.CreatedDate), (a.CreatedDate), (c.CreatedDate)) Thanks in advance for your help. Here's the full query:
WITH GroupWithLastActivityDate AS (
SELECT DISTINCT
g.Id
,g.GroupName
,g.GroupDescription
,g.CreatedDate
,g.ApartmentComplexId
,(SELECT MAX(X)
FROM (VALUES (g.CreatedDate), (a.CreatedDate), (c.CreatedDate)) AS AllDates(X)) AS LastActivityDate
FROM Groups g
LEFT OUTER JOIN Activities a
on g.Id = a.GroupId
LEFT OUTER JOIN Comments c
on a.Id = c.ActivityId
WHERE g.IsActive = 1
)
SELECT
GroupId = g.Id
,g.GroupName
,g.GroupDescription
,g.ApartmentComplexId
,NumberOfActivities = COUNT(DISTINCT a.Id)
,g.CreatedDate
,LastActivityDate = Max(g.LastActivityDate)
FROM GroupWithLastActivityDate g
INNER JOIN Activities a
on g.Id = a.GroupId
WHERE a.IsActive = 1
GROUP BY g.Id
,g.GroupName
,g.GroupDescription
,g.CreatedDate
,g.ApartmentComplexId
I should add that for now I've constructed a view with this query (plus some other stuff) which I'm querying with a SqlQuery.

TSQL Msg 1013 "Use correlation names to distinguish them."

I looked trough many suggestions and can't figure how to solve this one for the last two hours.
SET DATEFORMAT DMY
DECLARE #Source DATETIME = '01/01/2001'
DECLARE #Destenaition DATETIME = '01/01/2020'
SELECT ST.[Group],
ST.Shop,
SUM(ST.Purchased) AS Total,
CHG.Charged
FROM (SELECT Personals.Groups.[Name] AS 'Group',
Cards.vPurchases.PersonalID,
Personals.Registry.[Name],
SUM(Cards.vPurchases.Ammont) AS Purchased,
Cards.vPurchases.ShopName AS Shop
FROM Cards.vPurchases
INNER JOIN Personals.Registry
ON Personals.Registry.Id = Cards.vPurchases.PersonalID
INNER JOIN Personals.Groups
ON Personals.Registry.[Group] = Personals.Groups.Id
INNER JOIN Personals.Groups
ON Personals.Groups.Id = CHG.GroupID
WHERE Cards.vPurchases.[TimeStamp] >= #Source
AND Cards.vPurchases.[TimeStamp] <= #Destenaition
GROUP BY Cards.vPurchases.PersonalID,
Personals.Registry.[Name],
Personals.Groups.[Name],
Cards.vPurchases.ShopName) ST,
(SELECT PG.Id AS GroupID,
SUM(Cards.vCharges.Amount) AS Charged
FROM Cards.vCharges
INNER JOIN Personals.Registry
ON Personals.Registry.Id = Cards.vCharges.PersonalID
INNER JOIN Personals.Groups AS PG
ON Personals.Registry.[Group] = PG.Id
WHERE Cards.vCharges.[TimeStamp] >= #Source
AND Cards.vCharges.[TimeStamp] <= #Destenaition
GROUP BY Personals.Groups.[Name]) AS CHG
GROUP BY ST.Shop,
ST.[Group]
And then I get this error:
Msg 1013, Level 16, State 1, Line 6 The objects "Personals.Groups" and
"Personals.Groups" in the FROM clause have the same exposed names. Use
correlation names to distinguish them.
Thanks.
You are using the table Personals.Groups two times in the first sub query.
If you really mean to have the table Personals.Groups you need to give them an alias that you then use instead of the table names in the rest of the query.
INNER JOIN Personals.Groups as PG1
and
INNER JOIN Personals.Groups as PG2
If you only need one you can combine the on clauses to use just one instead.
INNER JOIN Personals.Groups
ON Personals.Registry.[Group] = Personals.Groups.Id and
Personals.Groups.Id = CHG.GroupID