Sql query with 2 conditions - sql

i have these tables:
tblCountry - country_number , country_name
tblDivingClub - club_number , country_number(FK)
tblDiver - diver_number, diver_name, startWorkingDate, endrtWorkingDate.
tblWorks_for -diver_number(FK), club_number(FK)
i need to write a query, without views or temp tables, that will diplay a lits of countries with the fields: country_number , country_name, and the number of diving clubs in that country which have 25 or more working divers at the moment (end working date IS NULL).
thats the code i wrote so far:
SELECT country_number, country_name,
( SELECT count(distinct tblDivingClub.number)
FROM tblDivingClub
inner join tblCountry on tblDivingClub.country = tblCountry.country_number
WHERE (
( SELECT count(tblWorks_for.diver_number)
FROM tblWorks_for
INNER JOIN tblDivingClub on tblWorks_for.club_number = tblDivingClub.number
WHERE tblWorks_for.end_working_date IS null
and tblDivingClub.number = tblWorks_for.club_number) >25)
) as number_of_clubs
FROM tblCountry
INNER JOIN tblDivingClub on tblCountry.country_number = tblDivingClub.country
WHERE tblCountry.country_number = tblDivingClub.country
GROUP by country_number, country_name

It's a good thing SQL anticipates the need for aggregate conditionals - if you suspected there must be a much easier way, you were right. I think you want something like:
SELECT country_number, country_name, count(distinct tblDivingClub.number)
FROM tblCountry
INNER JOIN tblDivingClub on tblCountry.country_number = tblDivingClub.country
WHERE tblCountry.country_number = tblDivingClub.country
GROUP by country_number, country_name
HAVING count(case when tblWorks_for.end_working_date IS null then 1 else null end) > 25

Try something like this:
SELECT country_number, country_name, COUNT(DISTINCT club_number)
FROM
(
SELECT tc.country_number, tc.country_name, tdc.club_number, count(*) as tot_cnt
FROM tblCountry tc
INNER JOIN tblDivingClub AS tdc ON tdc.country_number = tc.country_number
INNER JOIN tblWorks_for AS tw ON tw.club_number = tdc.club_number
INNER JOIN tblDiver AS td ON td.diver_number = tw.diver_number
WHERE endrtWorkingDate IS NULL
GROUP BY tc.country_number, tc.country_name, tdc.club_number
HAVING count(*) >= 25
) as der
GROUP BY country_number, country_name;

Related

(closed)How to use groupy by with subquery which join table?

I have no idea how to group by by the column from subquery.
I want to group by languageas below:
Here is my code:
select a.name, count(a.language) as count
from
(select
temp2.name,
countrylanguage.language
from
countrylanguage
right join
temp2
on
temp2.code = countrylanguage.countrycode
) as a
group by a.language;
Edited
I got a solution as below:
select temp2.name, count(countrylanguage.language)
from countrylanguage
join temp2 on temp2.code = countrylanguage.countrycode
group by temp2.name;
You can try below - you don't need any subquery
select temp2.name,count(countrylanguage.language)
from countrylanguage join temp2
on temp2.code = countrylanguage.countrycode
group by temp2.name
Table data :
SELECT * FROM countrylanguage
SELECT * FROM temp2
SELECT a.[Name], SUM(CASE WHEN a.[language] IS NULL THEN 0 ELSE 1 END) language_count
FROM
(SELECT
temp2.[Name],
countrylanguage.[language]
FROM temp2
LEFT JOIN countrylanguage ON temp2.code = countrylanguage.countrycode) a
GROUP BY a.name

Oracle SQL Correlated subquery - Returning count(*) in some columns

I have my initial statement which is :
SELECT TEAM.ID PKEY_SRC_OBJECT,
TEAM.MODF_DAT UPDATE_DATE,
TEAM.MODF_USR UPDATED_BY,
PERSO.FIRST_NAM FISRT_NAME
FROM TEAM
LEFT OUTER JOIN PERSO ON (TEAM.ID=PERSO.TEAM_ID)
I want to calculate some "flags" and return them in my initial statement.
There are 3 flags which can be calculated like this :
1) Flag ISMASTER:
SELECT Count(*)
FROM TEAM_TEAM_REL A, TEAM B
WHERE B.PARTY_PTY_ID = A.RLTD_TEAM_ID
AND CODE = 'Double';
2) Flag ISAGENT:
SELECT Count(*)
FROM TEAM_ROL_REL A, TEAM B
WHERE B.PARTY_PTY_ID = A.TEAM_ID;
3) Flag NUMPACTS:
SELECT Count(*)
FROM TEAM_ROL_REL A,
TEAM_ROL_POL_REL B,
PERSO_POL_STA_REL C,
TEAM D
WHERE A.ROL_CD IN ('1','2')
AND A.T_ROL_REL_ID = B.P_ROL_REL_ID
AND B.P_POL_ID = C.P_POL_ID
AND C.STA_CD = 'A'
AND D.PARTY_PTY_ID = A.TEAM_ID;
To try to achieve this, I've updated my initial statement like this :
WITH ABC AS (
SELECT TEAM.ID PKEY_SRC_OBJECT,
TEAM.MODF_DAT UPDATE_DATE,
TEAM.MODF_USR UPDATED_BY,
PERSO.FIRST_NAM FISRT_NAME
FROM TEAM
LEFT OUTER JOIN PERSO ON (TEAM.ID=PERSO.TEAM_ID)
)
SELECT ABC.*, MAST.ISMASTER, AGENT.ISAGENT, PACTS.NUMPACTS FROM ABC
LEFT OUTER JOIN (
select
RLTD_TEAM_ID,
Count(RLTD_TEAM_ID) OVER (PARTITION BY RLTD_TEAM_ID) as ISMASTER
FROM TEAM_TEAM_REL
WHERE CODE = 'Double'
) MAST
ON ABC.PKEY_SRC_OBJECT = MAST.RLTD_TEAM_ID
LEFT OUTER JOIN (
select
TEAM_ID,
Count(TEAM_ID) OVER (PARTITION BY TEAM_ID) as ISAGENT
FROM TEAM_ROL_REL
) AGENT
ON ABC.PKEY_SRC_OBJECT = AGENT.TEAM_ID
LEFT OUTER JOIN (
select
TEAM_ID,
Count(TEAM_ID) OVER (PARTITION BY TEAM_ID) as NUMPACTS
FROM TEAM_ROL_REL, TEAM_ROL_POL_REL, PERSO_POL_STA_REL
WHERE TEAM_ROL_REL.ROL_CD IN ('1','2')
AND TEAM_ROL_REL.T_ROL_REL_ID = TEAM_ROL_POL_REL.P_ROL_REL_ID
AND TEAM_ROL_POL_REL.P_POL_ID = PERSO_POL_STA_REL.P_POL_ID
AND PERSO_POL_STA_REL.STA_CD = 'A'
) PACTS
ON ABC.PKEY_SRC_OBJECT = PACTS.TEAM_ID;
For the two first flags (ISMASTER and ISAGENT) I get the result in less than 1min, but for the last flag (NUMPACTS) it runs few minutes without provide any result.
I think my statement is too heavy, maybe I should do it in a totally different way.
I think you have perhaps over complicated things.
You could do this (assuming I have understood your requirements correctly) like so:
WITH ttr AS (SELECT rltd_team_id,
COUNT(*) is_master
FROM team_team_rel
AND CODE = 'Double'
GROUP BY rltd_team_id),
trr AS (SELECT team_id,
COUNT(*) is_agent
FROM team_rol_rel
GROUP BY team_id)
pacts AS (SELECT trr1.team_id,
COUNT(*) num_pacts
FROM team_rol_rel trr1
INNER JOIN team_rol_pol_rel trpr ON (trr1.t_rol_rel_id = trpr.p_rol_rel_id)
INNER JOIN perso_pol_sta_rel ppsr ON (trpr.p_pol_id = ppsr.p_pol_id
WHERE trr1.rol_cd IN ('1', '2')
AND ppsr.st_cd = 'A'
GROUP BY trr1.team_id)
SELECT t.id pkey_src_object,
t.modf_dat update_date,
t.modf_usr updated_by,
p.first_nam first_name,
ttr.is_master,
trr.is_agent,
pacts.num_pacts
FROM team t
LEFT OUTER JOIN perso p ON t.id = p.team_id
LEFT OUTER JOIN ttr ON t.party_pty_id = ttr.rltd_team_id
LEFT OUTER JOIN trr ON t.party_pty_id = trr.team_id
LEFT OUTER JOIN pacts ON t.pkey_src_object = pacts.team_id;
N.B. untested, since you didn't provide any test data.

Nested Subqueries with Group By

Having trouble with this one. Getting syntax error at the arrow. I'm using subqueries on purpose. I'm wondering if it's possible to mix 'where' and 'having'?
;with books_not_ordered as
(
select BK.book_id
from bkinfo.books BK
where BK.book_id not in
(
select OD.book_id
from bkorders.order_details OD
)
)
select AU.author_id, AU.author_name_last
from bkinfo.authors AU
where exists
(
select BAU.author_id, count(*) as NumBooks
from bkinfo.book_authors BAU
group by BAU.author_id
having count(*) > 1
==>where AU.author_id = BAU.author_id
and
BAU.book_id in
(
select BK.book_id
from bkinfo.books BK
where BK.book_id in
(
select cte.book_id
from books_not_ordered cte
)
)
)
;
go
The where clause should come before your group by and having
select BAU.author_id, count(*) as NumBooks
from bkinfo.book_authors BAU
where AU.author_id = BAU.author_id
group by BAU.author_id
having count(*) > 1
Assuming that you are trying to get "The authors of the books that are not in order_details table, but who have written more than one book". The following query should work.
SELECT AU.author_id, AU.author_name_last
FROM bkinfo.books BK
JOIN bkinfo.book_authors BAU ON BAU.author_id = BK.author_id
JOIN bkinfo.authors AU ON BAU.author_id = AU.author_id
LEFT OUTER JOIN bkorders.order_details OD ON BK.book_id = OD.book_id
WHERE OD.book_id IS NULL
GROUP BY AU.author_id, AU.author_name_last
HAVING COUNT(BK.Book_id) > 1

Complex Full Outer Join

Sigh ... can anyone help? In the SQL query below, the results I get are incorrect. There are three (3) labor records in [LaborDetail]
Hours / Cost
2.75 / 50.88
2.00 / 74.00
1.25 / 34.69
There are two (2) material records in [WorkOrderInventory]
Material Cost
42.75
35.94
The issue is that the query incorrectly returns the following:
sFunction cntWO sumLaborHours sumLaborCost sumMaterialCost
ROBOT HARNESS 1 12 319.14 236.07
What am I doing wrong in the query that is causing the sums to be multiplied? The correct values are sumLaborHours = 6, sumLaborCost = 159.57, and sumMaterialCost = 78.69. Thank you for your help.
SELECT CASE WHEN COALESCE(work_orders.location, Work_Orders_Archived.location) IS NULL
THEN '' ELSE COALESCE(work_orders.location, Work_Orders_Archived.location) END AS sFunction,
(SELECT COUNT(*)
FROM work_orders
FULL OUTER JOIN Work_Orders_Archived
ON work_orders.order_number = Work_Orders_Archived.order_number
WHERE COALESCE(work_orders.order_number, Work_Orders_Archived.order_number) = '919630') AS cntWO,
SUM(Laborhours) AS sumLaborHours,
SUM(LaborCost) AS sumLaborCost,
SUM(MaterialCost*MaterialQuanity) AS sumMaterialCost
FROM work_orders
FULL OUTER JOIN Work_Orders_Archived
ON work_orders.order_number = Work_Orders_Archived.order_number
LEFT OUTER JOIN
(SELECT HoursWorked AS Laborhours, TotalDollars AS LaborCost, WorkOrderNo
FROM LaborDetail) AS LD
ON COALESCE(work_orders.order_number, Work_Orders_Archived.order_number) = LD.WorkOrderNo
LEFT OUTER JOIN
(SELECT UnitCost AS MaterialCost, Qty AS MaterialQuanity, OrderNumber
FROM WorkOrderInventory) AS WOI
ON COALESCE(work_orders.order_number, Work_Orders_Archived.order_number) = WOI.OrderNumber
WHERE COALESCE(work_orders.order_number, Work_Orders_Archived.order_number) = '919630'
GROUP BY CASE WHEN COALESCE(work_orders.location, Work_Orders_Archived.location) IS NULL
THEN '' ELSE COALESCE(work_orders.location, Work_Orders_Archived.location) END
ORDER BY sFunction
Try using the SUM function inside a derived table subquery when doing the full join to "WorkOrderInventory" like so...
select
...
sum(hrs) as sumlaborhrs,
sum(cost) as sumlaborcost,
-- calculate material cost in subquery
summaterialcost
from labordetail a
full outer join
(select ordernumber, sum(materialcost) as summaterialcost
from WorkOrderInventory
group by ordernumber
) b on a.workorderno = b.ordernumber
i created a simple sql fiddle to demonstrate this (i simplified your query for examples sake)
Looks to me that work_orders and work_orders_archived contains the same thing and you need both tables as if they were one table. So you could instead of joining create a UNION and use it as if it was one table:
select location as sfunction
from
(select location
from work_orders
union location
from work_orders_archived)
Then you use it to join the rest. What DBMS are you on? You could use WITH. But this does not exist on MYSQL.
with wo as
(select location as sfunction, order_number
from work_orders
union location, order_number
from work_orders_archived)
select sfunction,
count(*)
SUM(Laborhours) AS sumLaborHours,
SUM(LaborCost) AS sumLaborCost,
SUM(MaterialCost*MaterialQuanity) AS sumMaterialCost
from wo
LEFT OUTER JOIN
(SELECT HoursWorked AS Laborhours, TotalDollars AS LaborCost, WorkOrderNo
FROM LaborDetail) AS LD
ON COALESCE(work_orders.order_number, Work_Orders_Archived.order_number) = LD.WorkOrderNo
LEFT OUTER JOIN
(SELECT UnitCost AS MaterialCost, Qty AS MaterialQuanity, OrderNumber
FROM WorkOrderInventory) AS WOI
ON COALESCE(work_orders.order_number, Work_Orders_Archived.order_number) = WOI.OrderNumber
where wo.order_number = '919630'
group by sfunction
order by sfunction
The best guess is that the work orders appear more than once in one of the tables. Try these queries to check for duplicates in the two most obvious candidate tables:
select cnt, COUNT(*), MIN(order_number), MAX(order_number)
from (select order_number, COUNT(*) as cnt
from work_orders
group by order_number
) t
group by cnt
order by 1;
select cnt, COUNT(*), MIN(order_number), MAX(order_number)
from (select order_number, COUNT(*) as cnt
from work_orders_archived
group by order_number
) t
group by cnt
order by 1;
If either returns a row where cnt is not 1, then you have duplicates in the tables.

how to get the count in SQL Server?

I have tried a lot to figure how to get the count from two tables with respect to master table
I have three tables
Using these table values I need to get this output..
Tried but could get the desired result
http://en.wikipedia.org/wiki/Join_(SQL)
SQL - LEFT OUTER JOIN and WHERE clause
http://forums.devshed.com/oracle-development-96/combination-of-left-outer-join-and-where-clause-383248.html
You have to first GROUP BY in subqueries, then JOIN to the main table:
SELECT
a.AttributeId
, COALECSE(cntE, 0) AS cntE
, COALECSE(cntM, 0) AS cntM
FROM
AttributeMaster AS a
LEFT JOIN
( SELECT
AttributeId
, COUNT(*) AS cntE
FROM
EmployeeMaster
GROUP BY
AttributeId
) em
ON em.AttributeId = a.AttributeId
LEFT JOIN
( SELECT
AttributeId
, COUNT(*) AS cntM
FROM
MonthlyDerivedMaster
GROUP BY
AttributeId
) mdm
ON mdm.AttributeId = a.AttributeId
SELECT AttributeId,
(SELECT COUNT(Eid) FROM EmployeeMaster WHERE AttributeMaster.AttributeId = EmployeeMaster.AttributeId) as master_eid,
(SELECT COUNT(Eid) FROM MonthnlyDerivedMaster WHERE AttributeMaster.AttributeId = MonthnlyDerivedMaster.AttributeId) as monthly_eid
FROM AttributeMaster