Need query to determine number of attachments for each issue - sql-server

I have a database in SQL Server that has three tables: Issues, Attachments, and Requestors. I need a single query that returns all the columns contained in the "Issues" and "Attachments" tables. Listed below is the query that I've created, but it's not working as expected:
SELECT A.*,
B.*,
SubQuery.attachmentcount
FROM [DB].[dbo].[issues] AS A
FULL OUTER JOIN [DB].[dbo].[requestors] AS B
ON A.issue_id = B.issue_id,
(SELECT Count(attachments.attachment_id) AS AttachmentCount
FROM issues
LEFT OUTER JOIN attachments
ON issues.issue_id = attachments.issue_id
WHERE attachments.attachment_status = 1
GROUP BY issues.issue_id) AS SubQuery;
Pictures describing the three tables are listed below:
Any ideas on how to fix my query?
Thanks,

"I need a single query that returns all the columns contained in the "Issues" and "Attachments" tables".
Based on this sentence try this:
SELECT A.Issue_ID, I.Issue_Name,r.Name, COUNT(A.attachment_id) AS Count
FROM Attachments as A
INNER JOIN Issues I on I.issue_id = A.issue_id
INNER JOIN requestors as R on A.issue_id = R.requestor_id
WHERE A.attachment_status = 1
GROUP BY A.Issue_ID, I.Issue_Name, r.Name
--Specify all columns by name (don't use *)

Keep It Simple and Try This!
SELECT i.Issue_ID, i.Issue_Name, COUNT(a.attachment_id) AS AttachmentCount
FROM attachments a JOIN
issues i ON
i.issue_id = a.issue_id
WHERE a.attachment_status = 1
GROUP BY i.Issue_ID, i.Issue_Name
Add your Desired Columns in Both Select List and Group By Clause and you are done.

Related

Getting team names when given two team IDs

I need to get a Select query that lets me display team names instead of IDs.
I store information about teams(ID, Name); match(ID, ht_ID(FK to teams(ID), at_ID(FK to teams(ID)); match_results(ID, Match_ID(FK to match(ID), Results(varchar)) each in seperate table as shown above.
For example, if I do -
select match.ID, match.ht_ID, match.at_ID, match_results.Results from match_results
join match on mattch.ID = match_results.Match_ID
This query is going to output ID, Home team id, Away team ID and the score. How can I write the query so I can see the team names instead of team ids? Thanks!
You need to join twice onto your teams table using a different alias each time
select match.ID, match.ht_ID, ht.Name as ht_Name, match.at_ID, at.Name as at_Name, match_results.Results
from match_results
join match on mattch.ID = match_results.Match_ID
join teams ht on match.ht_ID = ht.ID
join teams at on mtach.at_ID = at.ID
You should use aliases for the table names and the selected fields as well to be able track and pick columns for the stated tables and advise you use left you get specific rows.
SELECT DISTINCT mr.name as match_results, ht.name as home_team,at.name as
away_team FROM match_results mr LEFT JOIN match m ON mr.match_id = m.id
LEFT JOIN teams ht m.ht_id = ht.id LEFT JOIN teams at m.at_id = at.id;

Understanding DISTINCT vs DISTINCT ON vs Group by

I have a query which returns a set of 'records'.
The result is always from the same table, and should always be unique. It has a set of inner joins to filter the rows down to the appropriate subset.
The query is returning roughly 10 columns.
However, I found that it was returning duplicate rows, so I added select distinct to the query, which solved the duplication problem but has significant performance issues.
My understanding is that select distinct on (records.id), id... will return the same result in this case, as all duplicates would have the same primary key, and seems to be about twice as fast.
My other tests show that group by records.id is even faster again, and seems to do the same thing?
Am I correct that all three of these approaches will always return the same set of single table records?
Also, is there an easy way to compare the results of different approaches to ensure the set is being returned?
Here is my query:
SELECT DISTINCT records.*
FROM records
INNER JOIN records parents on parents.path #> records.path
INNER JOIN record_types ON record_types.id = records.record_type_id
INNER JOIN user_roles ON user_roles.record_id = parents.id AND user_roles.user_id = _user_id
INNER JOIN memberships ON memberships.role_id = user_roles.role_id
INNER JOIN roles ON roles.id = memberships.role_id
INNER JOIN groups ON memberships.group_id = groups.id AND
groups.id = record_types.view_group_id
Any individual record can have tree of 'parent' records. This is done using the ltree plugin. Effectively, we are looking to see if the user has a role which is in a group which is defined as the 'view group' for either the current record, or any of the parents. The query is actually a function, and _user_id is being passed in.
Since you are only selecting from records, you don't need DISTINCT; the records are already distinct (I presume).
So the duplicates you encounter could be caused by all the joins, for instance if more than one role or group membership matches one of your records, the same record will be combined with each of these references.
SELECT *
FROM records r
WHERE EXISTS (
SELECT *
FROM records pa on pa.path #> r.path
JOIN record_types typ ON typ.id = r.record_type_id
JOIN user_roles ur ON ur.record_id = pa.id AND ur.user_id = _user_id
JOIN memberships mem ON mem.role_id = ur.role_id
JOIN roles ON roles.id = mem.role_id
JOIN groups gr ON mem.group_id = gr.id AND gr.id = typ.view_group_id
)
;

How to get column value of join query in SSRS?

I have select join query for generating report in SSRS. Query is working fine in SQL Server but as I add same query as dataset in SSRS and try to get rows count using CountRows() function it always return 0 (Zero). I'm not getting where my query is going wrong.
SQL Query
SELECT PR.NAME
FROm innovator.PROJECT PR
INNER JOIN innovator.PROJECT_RISK LPR ON LPR.SOURCE_ID = Pr.ID
INNER JOIN innovator.RISK_MANAGEMENT LR ON LR.id = LPR.RELATED_ID
Inner join innovator.PROGRAM_PROJECT P ON PR.ID = P.RELATED_ID
Inner Join innovator.PROGRAM PP ON P.SOURCE_ID = PP.ID
WHERE pp.ID = #Id
Fetching total count using CountRows() for Textbox
=CountRows(Fields!NAME.Value, "DataSetRisk")
DataSetRisk is Dataset name and Name is column name of Project Table
Use the CountRows function. For example
=CountRows("MyDataset")
Example : =CountRows("DataSetRisk")
will give you the number of rows in MyDataSet.
Try something a little simpler: Count(Fields!NAME.Value) as a column. This assumes, of course, that field name actually is populated. If the column is in separate groups, it will provide a count for each group, otherwise it will count for the entire report.

How to compare the results of two separate queries that have a common field in Sql Server?

Maybe it's because it's Friday but I can't seem to get this and it feels like it should be really really easy.
I have one result set (pulls the data from multiple tables) that gives me the following result set:
Room Type | ImageID | Date
The next query (pulled from separate tables than above) result give me :
ImageID | Date | Tagged
I just want to compare the results to see which imageid's are common between the two results, and which fall into each list separately.
I have tried insert the results from each into temp tables and do a join on imageid but sql server does NOT like that. Ideally I would like a solution that allows me to do this without creating temp tables.
I researched using union but it seems that because the two results don't have the same columns I avoided that route.
Thanks!
You can do this a number of different ways, for instance you can use either a inner join or intersect using the two sets as derived tables.
select ImageID from (your_first_query)
intersect
select ImageID from (your_second_query)
or
select query1.ImageID
from (your_first_query) query1
inner join (your_second_query) query2 on query1.ImageID = query2.ImageID
You don't explain why SQL-Server does not like performing a join on ImageId. Shouldn't be a problem. As to your first question, you need to transform your two queries into subqueries and perform a Full Out Join on them:
Select * from
(Select Room Type, ImageID, Date ...) T1 Full Outer Join
(Select ImageID, Date, Tagged ...) T2 on T1.ImageId = T2.ImageId
The analysis of Null values on both side of the join should give you what you want.
SELECT TableA.ImageID
FROM TableA
WHERE TableA.ImageID
IN (SELECT TableB.ImageID FROM TableB)
select q1.ImageID
from (your_first_query) q1
WHERE EXISTS (select 1
from (your_second_query)
WHERE ImageID = q1.ImageID)

SQL Server JOIN adds results?

I have a table which basically contains a Person_ID, Action, TimeStamp and using Microsoft ReportBuilder I have a report which tables each Person and the COUNT for their Actions.
Person Action X ActionY
1 3 5
2 0 4
Now I need to filter the results to only show people in a certain group which is defined by another table containing Person_ID, Group_ID.
When I do a JOIN and filter results based on the Group_ID = x the counts are very high, although it does filter correctly.
I run the query manually in SQL Server Manager and it is returning the same row multiple times?
EDIT:
My current SQL is
select t1.personid, t1.action, t2.personid, t2.groupid
from t1
inner join t2 on t1.personid = t2.personid
where t2.groupid = 1
This returns each line multiple times, forgetting the count part as this is in the report builder I would like to understand why the same row is returned multiple times as this is what breaks the report.
Do a DISTINCT
SO..
SELECT PersonID, ActionX = COUNT(distinct varname), ActionY = SUM(distint varname)
FROM tblName1 a
INNER JOIN tblName2 b ON a.PersonID = b.PersonID
WHERE b.Group_ID = 'groupvar'

Resources