Can this subquery be written as a join and still get the same result set/number of rows? - sql

How do I write the below as a join and get the same number of rows?
SELECT
s.subjectid,
s.subjectname,
(SELECT
COUNT(*)
FROM dbo.Classes AS c
WHERE c.SubjectID = s.SubjectID
AND c.MondaySchedule = 1)
AS numofclasses
FROM dbo.subjects AS s
ORDER BY numofclasses DESC
I am trying to write it like below but getting a different answer:
SELECT
s.subjectid,
COUNT(ClassID) AS numberofclasses
FROM dbo.subjects AS s
LEFT JOIN dbo.classes AS c
ON s.SubjectID = c.SubjectID
WHERE c.MondaySchedule = 1
GROUP BY s.Subjectid
ORDER BY numberofclasses DESC

Move the where condition to the on condition. It is converting the outer join to an inner join:
select s.subjectid, count(ClassID) as numberofclasses
from dbo.subjects s left join
dbo.classes c
on s.SubjectID = c.SubjectID and c.MondaySchedule = 1
group by s.Subjectid
order by numberofclasses desc ;
This does assume that subjects(subjectid) is unique (or a primary key). If not, the two might return different results.

Related

How to create distinct count from queries with several tables

I am trying to create one single query that will give me a distinct count for both the ActivityID and the CommentID. My query in MS Access looks like this:
SELECT
tbl_Category.Category, Count(tbl_Activity.ActivityID) AS CountOfActivityID,
Count(tbl_Comments.CommentID) AS CountOfCommentID
FROM tbl_Category LEFT JOIN
(tbl_Activity LEFT JOIN tbl_Comments ON
tbl_Activity.ActivityID = tbl_Comments.ActivityID) ON
tbl_Category.CategoryID = tbl_Activity.CategoryID
WHERE
(((tbl_Activity.UnitID)=5) AND ((tbl_Comments.PeriodID)=1))
GROUP BY
tbl_Category.Category;
I know the answer must somehow include SELECT DISTINCT but am not able to get it to work. Do I need to create multiple subqueries?
This is really painful in MS Access. I think the following does what you want to do:
SELECT ac.Category, ac.num_activities, aco.num_comments
FROM (SELECT ca.category, COUNT(*) as num_activities
FROM (SELECT DISTINCT c.Category, a.ActivityID
FROM (tbl_Category as c INNER JOIN
tbl_Activity as a
ON c.CategoryID = a.CategoryID
) INNER JOIN
tbl_Comments as co
ON a.ActivityID = co.ActivityID
WHERE a.UnitID = 5 AND co.PeriodID = 1
) as caa
GROUP BY ca.category
) as ca LEFT JOIN
(SELECT c.Category, COUNT(*) as num_comments
FROM (SELECT DISTINCT c.Category, co.CommentId
FROM (tbl_Category as c INNER JOIN
tbl_Activity as a
ON c.CategoryID = a.CategoryID
) INNER JOIN
tbl_Comments as co
ON a.ActivityID = co.ActivityID
WHERE a.UnitID = 5 AND co.PeriodID = 1
) as aco
GROUP BY c.Category
) as aco
ON aco.CommentId = ac.CommentId
Note that your LEFT JOINs are superfluous because the WHERE clause turns them into INNER JOINs. This adjusts the logic for that purpose. The filtering is also very tricky, because it uses both tables, requiring that both subqueries have both JOINs.
You can use DISTINCT:
SELECT
tbl_Category.Category, Count(DISTINCT tbl_Activity.ActivityID) AS CountOfActivityID,
Count(DISTINCT tbl_Comments.CommentID) AS CountOfCommentID
FROM tbl_Category LEFT JOIN
(tbl_Activity LEFT JOIN tbl_Comments ON
tbl_Activity.ActivityID = tbl_Comments.ActivityID) ON
tbl_Category.CategoryID = tbl_Activity.CategoryID
WHERE
(((tbl_Activity.UnitID)=5) AND ((tbl_Comments.PeriodID)=1))
GROUP BY
tbl_Category.Category;

Finding the count

I have the following SQL query and need to know the count of companyid as I can see repeating data. How do I find the count of it. Following is the query
SELECT a.companyId 'companyId'
, i.orgDebtType 'orgDebtType'
, d.ratingTypeName 'ratingTypeName'
, c.currentRatingSymbol 'currentRatingSymbol'
, c.ratingStatusIndicator 'ratingStatusIndicator'
, g.qualifierValue 'qualifierValue'
, c.ratingdate 'ratingDate'
, h.value 'outlook'
FROM ciqRatingEntity a
JOIN ciqcompany com
on com.companyId = a.companyId
JOIN ciqratingobjectdetail b ON a.entitySymbolValue = b.objectSymbolValue
JOIN ciqRatingData c ON b.ratingObjectKey = c.ratingObjectKey
JOIN ciqRatingType d ON b.ratingTypeId = d.ratingTypeId
JOIN ciqRatingOrgDebtType i ON i.orgDebtTypeId=b.orgDebtTypeId
JOIN ciqRatingEntityData red ON red.entitySymbolValue=a.entitySymbolValue
AND red.ratingDataItemId='1' ---CoName
LEFT JOIN ciqRatingDataToQualifier f ON f.ratingDataId = c.ratingDataId
LEFT JOIN ciqRatingQualifiervalueType g ON g.qualifiervalueid = f.qualifierValueId
LEFT JOIN ciqRatingValueType h ON h.ratingValueId = c.outlookValueId
WHERE 1=1
AND b.ratingTypeId IN ( '130', '131', '126', '254' )
-- and a.companyId = #companyId
AND a.companyId IN
(SELECT distinct TOP 2000000
c.companyId
FROM ciqCompany c
inner join ciqCompanyStatusType cst on cst.companystatustypeid = c.companystatustypeid
inner join ciqCompanyType ct on ct.companyTypeId = c.companyTypeId
inner join refReportingTemplateType rep on rep.templateTypeId = c.reportingtemplateTypeId
inner join refCountryGeo rcg on c.countryId = rcg.countryId
inner join refState rs on rs.stateId = c.stateId
inner join ciqSimpleIndustry sc on sc.simpleIndustryId = c.simpleIndustryId
ORDER BY companyid desc)
ORDER BY companyId DESC, c.ratingdate, b.ratingTypeId, c.ratingStatusIndicator
This will list where there are duplicate companyID's
SELECT companyId, count(*) as Recs
FROM ciqCompany
GROUP BY ciqCompany
HAVING count(*) > 1
I understand that you wish to add a column to the query with the count of each companyId, you can use COUNT() OVER():
select count(a.companyId) over (partition by a.companyId) as companyCount,
<rest of the columns>
from ciqRatingEntity a
join <rest of the query>
This would return in each row the count of the companyId of that row without grouping the results.

How to use a column from joined table in a join with a subquery

What I'm trying to do is this:
SELECT *
FROM MainTable m
INNER JOIN JoinedTable j on j.ForeignID = m.ID
INNER JOIN (SELECT TOP 1 *
FROM SubQueryTable sq
WHERE sq.ForeignID = j.ID
ORDER BY VersionColumn DESC)
So basically, from SubQueryTable, I only want to retrieve a single row which has the maximum value for VersionColumn for all rows with a certain ID that I can get from JoinedTable.
T-SQL doesn't let me do this, what's a good way to solve this problem?
What I'm trying to prevent is loading the entire SubQueryTable and doing the filtering when it's too late as in....
SELECT *
FROM MainTable m
INNER JOIN JoinedTable j on j.ForeignID = m.ID
INNER JOIN (SELECT TOP 1 *
FROM SubQueryTable sq
ORDER BY VersionColumn DESC) sj ON sj.ForeignID = j.ID
I fear this second version performs the very slow subquery first and only filters it when it has loaded all the rows, but I want to filter sooner.
Any thoughts?
This will perform well if you have index on VersionColumn
SELECT *
FROM MainTable m
INNER JOIN JoinedTable j on j.ForeignID = m.ID
CROSS APPLY (SELECT TOP 1 *
FROM SubQueryTable sq
WHERE sq.ForeignID = j.ID
ORDER BY VersionColumn DESC) sj
Answer :
Hi,
Below query I have created as per your requirement using Country, State and City tables.
SELECT * FROM (
SELECT m.countryName, j.StateName,c.CityName , ROW_NUMBER() OVER(PARTITION BY c.stateid ORDER BY c.cityid desc) AS 'x'
FROM CountryMaster m
INNER JOIN StateMaster j on j.CountryID = m.CountryID
INNER JOIN dbo.CityMaster c ON j.StateID = c.StateID
) AS numbered WHERE x = 1
Below is your solution and above is only for your reference.
SELECT * FROM (
SELECT m.MainTablecolumnNm, j.JoinedTablecolumnNm,c.SubQueryTableColumnName , ROW_NUMBER()
OVER(PARTITION BY sj.ForeignID ORDER BY c.sjID desc) AS 'abc'
FROM MainTable m
INNER JOIN JoinedTable j on j.ForeignID = m.ID
INNER JOIN SubQueryTable sj ON sj.ForeignID = j.ID
) AS numbered WHERE abc = 1
Thank you,
Vishal Patel

Merge 2 SQL query CodeIgniter

I would like to merge these 2 queries to retrieve my datas in a view :
QUERY 1 :
$query = $this->db->query('SELECT ft_upload_data.*, ft_categories.*, ft_categories.category_name
FROM ft_upload_data
LEFT JOIN assigned_categories ON assigned_categories.ft_upload_data_id = ft_upload_data.post_id
LEFT JOIN ft_categories ON ft_categories.cat_id = assigned_categories.ft_categories_id
ORDER BY ft_upload_data.rank ASC
');
return $query->result();
QUERY 2 :
$query2 = $this->db->query('SELECT a.post_id,
COUNT(*) AS num_comments
FROM ft_upload_data a
JOIN ft_comments c ON c.post_id = a.post_id
GROUP BY a.post_id');
return $query2->result();
I can't figure it out :/ Any ideas to trick this?
Thanks !
The simplest (but not necessarily the most efficient) way would be to do it in an in-line query:
SELECT ft_upload_data.*, ft_categories.*,
(SELECT COUNT(*)
FROM ft_comments c
where c.post_id = ft_upload_data.post_id) AS num_comments
FROM ft_upload_data
LEFT JOIN assigned_categories
ON assigned_categories.ft_upload_data_id = ft_upload_data.post_id
LEFT JOIN ft_categories
ON ft_categories.cat_id = assigned_categories.ft_categories_id
ORDER BY ft_upload_data.rank ASC
A more efficient way would be to join to the ft_comments table and group by post_id (assuming that this uniquely identifies ft_upload_data rows), like so:
SELECT ft_upload_data.post_id,
/* include the maximum of each required field from ft_upload_data and
ft_categories here, with appropriate aliases */
COUNT(*) AS num_comments
FROM ft_upload_data
LEFT JOIN assigned_categories
ON assigned_categories.ft_upload_data_id = ft_upload_data.post_id
LEFT JOIN ft_categories
ON ft_categories.cat_id = assigned_categories.ft_categories_id
LEFT JOIN ft_comments c
on c.post_id = ft_upload_data.post_id
GROUP BY ft_upload_data.post_id
ORDER BY max(ft_upload_data.rank) ASC

Left Join, Order by, MySQL Optimization

I have a query like this:
SELECT m...., a...., r....
FROM 0_member AS m
LEFT JOIN 0_area AS a ON a.user_id = (SELECT user_id
FROM `0_area`
WHERE user_id = m.id
ORDER BY sec_id ASC LIMIT 1)
LEFT JOIN 0_rank as r ON a.rank_id = r.id
WHERE m.login_userid = '$username'
The idea is to get the first row from 0_area table and hence the attempted inner join. However, it is not working as expected.
Between 0_area and 0_member, 0_member.id = 0_area.user_id. However, there are multiple rows of 0_area.user_id and I want the row having the lowest value of sec_id.
Any help please?
SELECT m...., a...., r....
FROM 0_member AS m
LEFT JOIN (SELECT user_id, min(sec_id) minsec
FROM `0_area`
GROUP BY user_id) g1 on g1.user_id=m.id
LEFT JOIN 0_area AS a ON a.user_id = g1.user_id and a.sec_id=minsec
LEFT JOIN 0_rank as r ON a.rank_id = r.id
WHERE m.login_userid = '$username'