I have a report that has a drillthrough subreport that runs multiple times when it has more than one relationship to a many to many item that has nothing to do with the subreport.
Main report query
SELECT DISTINCT
cat.CategoryName AS 'Category Name', sub.SubCategoryName AS 'SubCategory Name', cur.Status, cur.PastConsiderationFlag, cur.Model, cur.Version, cur.Vendor, cur.AvailableDate AS 'Available Date', cur.EndOfProduction AS 'End of Production',
cur.EndOfSupport AS 'End of Support', dep.DepartmentName AS 'Department Name', emp.FirstName + ' ' + emp.LastName AS 'Tech Owner', emp2.FirstName + ' ' + emp2.LastName AS 'Tech Contact',
cur.NumOfDevices AS '# of Devices', cur.UpgradeDuration AS 'Upgrade Duration', cur.FiscalConsideration AS 'Fiscal Consideration', cur.Description, cur.SupportingComments, cur.CurrencyId, STUFF
((SELECT ', ' + pl.PlatformName AS Expr1
FROM Platform AS pl LEFT OUTER JOIN
Currency_Platform AS cp ON cur.CurrencyId = cp.CurrencyId
WHERE (pl.PlatformId = cp.PlatformId) FOR XML PATH('')), 1, 1, '') AS 'Platforms', ISNULL(STUFF
((SELECT ', ' + cu2.Model AS Expr1
FROM Currency AS cu2 RIGHT OUTER JOIN
Currency_Dependency AS cd ON cur.CurrencyId = cd.CurrencyId
WHERE (cu2.CurrencyId = cd.DependencyId) FOR XML PATH('')), 1, 1, ''), 'N/A') AS 'Dependencies', ISNULL(STUFF
((SELECT ', ' + cu2.Model AS Expr1
FROM Currency AS cu2 RIGHT OUTER JOIN
Currency_Affected AS ca ON cur.CurrencyId = ca.CurrencyId
WHERE (cu2.CurrencyId = ca.AffectedId) FOR XML PATH('')), 1, 1, ''), 'N/A') AS 'Affected Apps', Currency_Platform.PlatformId
FROM Currency AS cur INNER JOIN
SubCategory AS sub ON cur.SubCategoryId = sub.SubCategoryId INNER JOIN
Category AS cat ON sub.CategoryId = cat.CategoryId LEFT OUTER JOIN
Employee AS emp ON cur.OwnerId = emp.EmployeeId LEFT OUTER JOIN
Employee AS emp2 ON cur.ContactId = emp2.EmployeeId LEFT OUTER JOIN
Department AS dep ON cur.PortfolioOwnerId = dep.DepartmentId LEFT OUTER JOIN
Currency_Platform ON cur.CurrencyId = Currency_Platform.CurrencyId
Even though it's a distinct select, the subreport will run equal to the amount of Platforms it belongs to. I'll include the Query for the subreport here.
;with cte as (
-- anchor elements: where curr.Status = 1 and not a dependent
select
CurrencyId
, Model
, Version
, ParentId = null
, ParentModel = convert(varchar(128),'')
, Root = curr.Model
, [Level] = convert(int,0)
, [ParentPath] = convert(varchar(512),Model + Version)
from dbo.Currency as curr
where curr.Status = 1
/* anchor's do not depend on any other currency */
and not exists (
select 1
from dbo.Currency_Dependency i
where curr.CurrencyId = i.DependencyId
)
-- recursion begins here
union all
select
CurrencyId = c.CurrencyId
, Model = c.Model
, Version = c.Version
, ParentId = p.CurrencyId
, ParentModel = convert(varchar(128),p.Model + p.Version)
, Root = p.Root
, [Level] = p.[Level] + 1
, [ParentPath] = convert(varchar(512),p.[ParentPath] + ' > ' + c.Model + ' ' + c.Version)
from dbo.Currency as c
inner join dbo.Currency_Dependency as dep
on c.CurrencyId = dep.DependencyId
inner join cte as p
on dep.CurrencyId = p.CurrencyId
)
select CurrencyId, ParentPath, Model + ' ' + Version AS 'Model' from cte
WHERE CurrencyId = #CurrencyId
When I run the subreport individually, everything is fine. When I open the subreport through the main report passing the CurrencyId as a parameter, it does so as many times as the amount of platforms it belongs to.
Is there a way I can correct this either by improving the queries, or as I would prefer, force the subreport to only run once no matter what?
Thanks so much for having a look.
You can use SQL Server Profiler to check the following things.
How many times and with what parameters is the subreport query has ran
How many values your first query returned
I don't think your problem is more about SSRS than it is about your T-SQL Code. I'm going to guess and say that the subreport object is in the report detail section of the report. That means that the subreport is going to render once for every row in the main queries dataset. I don't have any idea what your container report actually looks like but one option you have might be to include the subreport in the header or footer section and have it run off of a MAX(), MIN(), of a value that you know will be the same for every row.
Related
I have a stored procedure that I want to select a column if the applicationTypeId is in a list of IDs. I am trying to use the CASE statement but I don't know what I am doing wrong. I created a table and added the ApplicationTypeIds to it. The table name is #RelationshipsTypeApplicationId
In other words, what I am trying to do is the following:
If the applicationTypeId is in the #RelationshipsTypeApplicationId table
Join and select the Name column from the IGCRelationshipTypes table
Here is my original stored procedure
WITH AllCustomers AS
(
SELECT
app.ApplicationId,
cust.Name,
ApplicationTypes.TypeName AS ApplicationType,
ApplicationSources.ApplicationSourceName AS ApplicationSource,
CreatedDate = app.CreatedDate,
LastUpdateDate = app.StatusChangeDate,
app.StatusId,
InProgress = STUFF((SELECT ';'+#aw.ApplicationWorkflowName
FROM #aw
WHERE #aw.ApplicationId = app.ApplicationId
ORDER BY StepNumber
FOR XML PATH('')), 1, 1, ''),
ActionRequired = (SELECT top 1 1 FROM #aw
WHERE #aw.ApplicationId = app.ApplicationId
AND #aw.WorkflowStatusId = 6),
AccountId = STUFF((SELECT ';' + acct.AccountId
FROM #accounts AS acct
WHERE acct.ApplicationId = app.ApplicationId
ORDER BY acct.ParentAccountId
FOR XML PATH('')), 1, 1, '')
FROM
[dbo].[Applications] app
INNER JOIN
[dbo].[Customers] AS cust ON cust.CustomerId = app.CustomerId
INNER JOIN
[dbo].[ApplicationTypes] ON ApplicationTypes.ApplicationTypeId = app.ApplicationTypeId
INNER JOIN
[dbo].[ApplicationSources] ON ApplicationSources.ApplicationSourceId = app.ApplicationSourceId
WHERE
app.StatusId <> '4020-8901-64FFE33F06B1'
AND (#applicationTypeId IS NULL OR app.ApplicationTypeId = #applicationTypeId)
And here is what I updated:
WITH AllCustomers AS
(
SELECT
app.ApplicationId,
cust.Name,
ApplicationTypes.TypeName AS ApplicationType,
ApplicationSources.ApplicationSourceName AS ApplicationSource,
CreatedDate = app.CreatedDate,
LastUpdateDate = app.StatusChangeDate,
app.StatusId,
InProgress = STUFF((SELECT ';' + #aw.ApplicationWorkflowName
FROM #aw
WHERE #aw.ApplicationId = app.ApplicationId
ORDER BY StepNumber
FOR XML PATH('')), 1, 1, ''),
ActionRequired = (SELECT top 1 1 FROM #aw
WHERE #aw.ApplicationId = app.ApplicationId
AND #aw.WorkflowStatusId = 6),
AccountId = STUFF((SELECT ';' + acct.AccountId
FROM #accounts as acct
WHERE acct.ApplicationId = app.ApplicationId
ORDER BY acct.ParentAccountId
FOR XML PATH('')), 1, 1, ''),
CASE
WHEN app.ApplicationTypeId IN (SELECT * FROM #RelationshipsTypeApplicationId)
THEN relationshipType.Name
END
FROM
[dbo].[Applications] app
INNER JOIN
[dbo].[Customers] AS cust ON cust.CustomerId = app.CustomerId
INNER JOIN
[dbo].[ApplicationTypes] ON ApplicationTypes.ApplicationTypeId = app.ApplicationTypeId
INNER JOIN
[dbo].[ApplicationSources] ON ApplicationSources.ApplicationSourceId = app.ApplicationSourceId
INNER JOIN
[dbo].[IGCRelationshipTypes] AS relationshipType
ON CASE
WHEN app.ApplicationTypeId IN (SELECT * FROM #RelationshipsTypeApplicationId)
THEN (relationshipType.Name = #relationshipType)
END
WHERE
app.StatusId <> '4020-8901-64FFE33F06B1'
AND (#applicationTypeId IS NULL OR app.ApplicationTypeId = #applicationTypeId)
Here is a screenshot of the syntax error:
Can someone shed some light on what I am missing here?
CASE in T-SQL is an expression that returns a single scalar value, it is not for control of flow. See Dirty secrets of the CASE expression. You'll need something like this, but I don't have the energy to try to determine why you have a table named #RelationshipsTypeApplicationId with a single column (because you really shouldn't say IN (SELECT *)) or if you want to do something different when the match does not exist.
...
ON relationshipType.Name = CASE
WHEN app.ApplicationTypeId IN
(SELECT * FROM #RelationshipsTypeApplicationId)
THEN #relationshipType END
...
I have a table of data that shows multiple rows for a single piece of data. In the example below, I have a column called, "Location Type" that shows, "BH" and "TPI". BH and TPI each have a specific location shown in the "Location" column. Instead of having a new row for BH and TPI, I'd like two new columns that show the location data for that row. I included a couple of rows of data below. I suspect I need to use PIVOT here but I've been having a hard time figuring out where the PIVOT needs to come in. Could anybody provide some guidance or show me a solution?
Here's a sample of the data from the query.
API14
First Prod Date
Location Type
Location
43013540070000
2/8/2021
BH
Township 3S Range 4W Section 17 DUCHESNE County
43013540070000
2/8/2021
TPI
Township 3S Range 4W Section 18 DUCHESNE County
Here's the format I would like to see:
API14
First Prod Date
BH Location
TPI Location
43013540070000
2/8/2021
Township 3S Range 4W Section 17 DUCHESNE County
Township 3S Range 4W Section 18 DUCHESNE County
Here's my code so far:
DECLARE #SearchYear AS VARCHAR(4) = '2021'
DECLARE #SearchMonth AS VARCHAR(2) = '6'
SELECT
dbo.BuildAPI14(Well.WellID, Construct.SideTrack, Construct.Completion) AS 'API14',
CAST(ConstructDate.EventDate AS DATE) AS 'First Prod Date',
Loc.LocType AS 'Location Type',
CONCAT('Township ',LocExt.Township,LocExt.TownshipDir,' ','Range ',LocExt.Range,LocExt.RangeDir,' Section ',LocExt.Sec,' ',RefCounty.CountyName,' County') AS 'Location',
tblAPDTracker.SpacingRule AS 'Spacing Rule',
Lease.Number AS 'Entity Number',
WellHistory.WHComments AS 'Well History Comments'
FROM Well
LEFT JOIN Construct ON Construct.WellKey = Well.PKey
LEFT JOIN ConstructReservoir ON ConstructReservoir.ConstructKey = Construct.PKey
LEFT JOIN Lease ON Lease.Pkey = ConstructReservoir.LeaseKey
LEFT JOIN WellHistory ON WellHistory.WellKey = Construct.WellKey
LEFT JOIN tblAPDTracker ON LEFT(tblAPDTracker.APINO,10) = Well.WellID
LEFT JOIN Loc ON loc.ConstructKey = Construct.PKey AND Loc.LocType IN ('BH','TPI')
LEFT JOIN LocExt ON LocExt.LocKey = Loc.PKey
LEFT JOIN ConstructDate ON ConstructDate.ConstructKey = Construct.PKey AND ConstructDate.Event = 'FirstProduction'
LEFT JOIN RefCounty ON RefCounty.PKey = LocExt.County
WHERE
WorkType = 'ENTITY' AND
WellHistory.ModifyUser = 'UTAH\rachelmedina' AND
YEAR(WellHistory.ModifyDate) = #SearchYear AND
MONTH(WellHistory.ModifyDate) = #SearchMonth
GROUP BY
Well.WellID,
Construct.SideTrack,
Construct.Completion,
ConstructDate.EventDate,
Loc.LocType,
LocExt.Township,
LocExt.TownshipDir,
LocExt.Range,
LocExt.RangeDir,
LocExt.Sec,
RefCounty.CountyName,
tblAPDTracker.SpacingRule,
Lease.Number,
WellHistory.WHComments,
WellHistory.ModifyDate
ORDER BY
Well.WellId,
WellHistory.ModifyDate DESC
Select *
from
(
SELECT
dbo.BuildAPI14(Well.WellID, Construct.SideTrack, Construct.Completion) AS 'API14',
CAST(ConstructDate.EventDate AS DATE) AS 'First Prod Date',
Loc.LocType AS 'Location Type',
CONCAT('Township ',LocExt.Township,LocExt.TownshipDir,' ','Range ',LocExt.Range,LocExt.RangeDir,' Section ',LocExt.Sec,' ',RefCounty.CountyName,' County') AS 'Location' --,
-- tblAPDTracker.SpacingRule AS 'Spacing Rule',
-- Lease.Number AS 'Entity Number',
-- WellHistory.WHComments AS 'Well History Comments'
FROM Well
LEFT JOIN Construct ON Construct.WellKey = Well.PKey
LEFT JOIN ConstructReservoir ON ConstructReservoir.ConstructKey = Construct.PKey
LEFT JOIN Lease ON Lease.Pkey = ConstructReservoir.LeaseKey
LEFT JOIN WellHistory ON WellHistory.WellKey = Construct.WellKey
LEFT JOIN tblAPDTracker ON LEFT(tblAPDTracker.APINO,10) = Well.WellID
LEFT JOIN Loc ON loc.ConstructKey = Construct.PKey AND Loc.LocType IN ('BH','TPI')
LEFT JOIN LocExt ON LocExt.LocKey = Loc.PKey
LEFT JOIN ConstructDate ON ConstructDate.ConstructKey = Construct.PKey AND ConstructDate.Event = 'FirstProduction'
LEFT JOIN RefCounty ON RefCounty.PKey = LocExt.County
WHERE
WorkType = 'ENTITY' AND
WellHistory.ModifyUser = 'UTAH\rachelmedina' AND
YEAR(WellHistory.ModifyDate) = #SearchYear AND
MONTH(WellHistory.ModifyDate) = #SearchMonth
GROUP BY
Well.WellID,
Construct.SideTrack,
Construct.Completion,
ConstructDate.EventDate,
Loc.LocType,
LocExt.Township,
LocExt.TownshipDir,
LocExt.Range,
LocExt.RangeDir,
LocExt.Sec,
RefCounty.CountyName,
tblAPDTracker.SpacingRule,
Lease.Number,
WellHistory.WHComments,
WellHistory.ModifyDate
) p
pivot (min(p.Location) for [Location Type] in ([TPI], [BH])) pvt
The values in the pivoted column need an aggregation operator (sum, avg, min, max etc) so pick one like min or max which won't try to do anything with a string, but which will do something if you have multiple occurrences in the pivoting column (Location here).
I've also commented out the columns selected which don't appear in your sample results, which may affect what needs to appear in the GROUP BY clause.
Another alternative from pivot is to just re-join the tables using different aliases to differentiate from the "BH" vs "TPI" instances. I also simplified the longer table names with short aliases "w" for Well, "wh" for wellhouse, etc.
Also, by seeing the hierarchy on how A -> B -> C -> D tables helps identify where the related components are. Then I copied those out for the location downward.
I removed the location type as a column and group by since the query joins simultaneously to the BH and TPI respectively.
DECLARE #SearchYear AS VARCHAR(4) = '2021'
DECLARE #SearchMonth AS VARCHAR(2) = '6'
SELECT
dbo.BuildAPI14(w.WellID, c.SideTrack, c.Completion) API14,
CAST(cd.EventDate AS DATE) 'First Prod Date',
CONCAT('Township ', LocExtBH.Township, LocExtBH.TownshipDir,
' ','Range ', LocExtBH.Range, LocExtBH.RangeDir,
' Section ', LocExtBH.Sec,
' ', rcBH.CountyName, ' County') 'BH Location',
CONCAT('Township ', LocExtTPI.Township, LocExtTPI.TownshipDir,
' ','Range ', LocExtTPI.Range, LocExtTPI.RangeDir,
' Section ', LocExtTPI.Sec,
' ', rcTPI.CountyName, ' County') 'TPI Location',
ADP.SpacingRule 'Spacing Rule',
l.Number 'Entity Number',
wh.WHComments 'Well History Comments'
FROM
Well w
LEFT JOIN tblAPDTracker ADP
ON w.WellID = LEFT(trk.APINO,10)
LEFT JOIN Construct c
ON w.PKey = c.WellKey
LEFT JOIN ConstructReservoir cr
ON c.PKey = cr.ConstructKey
LEFT JOIN Lease l
ON cr.LeaseKey = l.Pkey
LEFT JOIN WellHistory wh
ON c.WellKey = wh.WellKey
LEFT JOIN ConstructDate cd
ON c.PKey = cd.ConstructKey
AND cd.Event = 'FirstProduction'
LEFT JOIN Loc LocBH
ON c.PKey = locBH.ConstructKey
AND LocBH.LocType = 'BH'
LEFT JOIN LocExt LocExtBH
ON LocBH.PKey = LocExtBH.LocKey
LEFT JOIN RefCounty rcBH
ON LocExtBH.County = rcBH.PKey
LEFT JOIN Loc LocTPI
ON c.PKey = LocTPI.ConstructKey
AND LocTPI.LocType = 'TPI'
LEFT JOIN LocExt LocExtTPI
ON LocTPI.PKey = LocExtTPI.LocKey
LEFT JOIN RefCounty rcTPI
ON LocExtTPI.County = rcTPI.PKey
WHERE
w.WorkType = 'ENTITY'
AND wh.ModifyUser = 'UTAH\rachelmedina'
AND YEAR(wh.ModifyDate) = #SearchYear
AND MONTH(wh.ModifyDate) = #SearchMonth
GROUP BY
w.WellID,
c.SideTrack,
c.Completion,
cd.EventDate,
LocExtBH.Township,
LocExtBH.TownshipDir,
LocExtBH.Range,
LocExtBH.RangeDir,
LocExtBH.Sec,
rcBH.CountyName,
ADP.SpacingRule,
l.Number,
wh.WHComments,
wh.ModifyDate
ORDER BY
w.WellId,
wh.ModifyDate DESC
I am writing select statement in SQL Server. I have to add a select query.
select
acct.AccountID,
acct.Username,
acct.LastNm + ', ' + acct.FirstNm as Name ,
acct.Lastlogin,
acct.email as Email,
(select acct2.FirstNm + ' ' + acct2.LastNm as Name from tblUserAccount acct2
join tblReviewers ra2 on acct2.AccountID = ra2.ReviwerID) as Reviewers
from tblUserAccount acct
I need to get more names from a table called tblReviwers. So 1 user from the tblUserAccount table could be associated with multiple reviews.
The tblReviewers only has 3 column AnalystID, ReviewerID, and Date. When I select on the JOIN between TblUserAccount and TblReviewers on a test AccountID = AnalystID, I can get multiple ReviewerIDs, which their firstname and lastname are located in the tblUserAccount. This is the reason why I use a select subquery
When I run the query, I get the following error
Subquery returned more than 1 value. This is not permitted when the
subquery follows =, !=, <, <= , >, >= or when the subquery is used as
an expression.
I am trying to write a VIEW to get a data.
Any help is greatly appreciated.
A query for a column name can only contain a single record result set. If you have an entry with multiple results causes that error.
I think you are missing disclosure of a possible extra component needed in the reviewers table, the who entered it. This will result in a query similar to the following.
The aliases and relations will appear obvious, but need to be confirmed for your actual structure.
select
EnterBy.AccountID,
EnterBy.Username,
EnterBy.LastNm + ', ' + EnterBy.FirstNm as Name ,
EnterBy.Lastlogin,
EnterBy.email as Email,
ReviewBy.FirstNm + ' ' + ReviewBy.LastNm as ReviewerName
from
tblReviewers r
tblUserAccount EnterBy
on r.AccountID = EnterBy.AccountID
tblUserAccount ReviewBy
on r.ReviwerID = ReviewBy.AccountID
REVISION BASED ON ADDITIONAL DATA
Based on providing the analystID on who entered, you should be good with
select
EnterBy.AccountID,
EnterBy.Username,
EnterBy.LastNm + ', ' + EnterBy.FirstNm as Name ,
EnterBy.Lastlogin,
EnterBy.email as Email,
STUFF(( Select
', [' + ReviewBy.LastNm + ', ' + ReviewBy.FirstNm + '] ' AS [text()]
From
tblReviewers r
JOIN tblUserAccount ReviewBy
on r.ReviwerID = ReviewBy.AccountID
where
r.AnaylstID = EnterBy.AccountID
For XML PATH('')), 1, 2, '' ) as AllReviewers
from
tblUserAccount EnterBy
You cannot have a column that contains multiple rows in a single result set, it just doesn't make sense from SQL perspective. Hence the error.
You should JOIN the tblReviewers table instead of subselecting it. That will yield all Reviewers. Then, JOIN again on the tblUserAccount table to get the name of the Reviewer, and you are all set.
SELECT
acct.AccountID,
acct.Username,
acct.LastNm + ', ' + acct.FirstNm as Name ,
acct.Lastlogin,
acct.email as Email,
acct2.LastNm + ', ' + acct2.FirstNm as ReviewerName ,
FROM tblUserAccount acct
JOIN tblReviewers revi
ON on acct.AccountID = revi.ReviewerID
JOIN tblUserAccount acct2
ON on acct2.AccountID = revi.AnalystID
Starting from Sql Server 2017, You can use something like STRING_AGG function, which combines values from multiple rows into a single string.
Then, your Reviewers column in your query might look like this:
(select STRING_AGG(Name, ',') from
(select acct2.FirstNm + ' ' + acct2.LastNm as Name from tblUserAccount acct2
join tblReviewers ra2 on acct2.AccountID = ra2.ReviwerID
where ra2.AnalystID = acct.AccountID)
) as Reviewers
In this case, names(first name + last name) of the reviewers for the current user will be separated by commas.
Subselects in select lists can only be used to return one value.
In your case, use joins
SELECT
a.AccountID,
a.Username,
a.LastNm + ', ' + a.FirstNm as Name ,
a.Lastlogin,
a.email as Email,
b.LastNm + ', ' + b.FirstNm as ReviewerName
FROM
tblUserAccount a
LEFT JOIN tblReviewers r ON a.AccountID = r.AnalystID
INNER JOIN tblUserAccount b ON r.ReviewerID = b.AccountID
I also used a LEFT JOIN to the reviewers table, in case there is no reviewer defined for an analyst.
You will get several rows per analyst, if more than one reviewer is assigned to it. Usually I solve this problem in the front-end by making a report that puts the main data in a group header (the analyst) and the related date (the reviewers) in the detail section of the report.
Starting with SQL Server 2017, you can also use the STRING_AGG function to concatenate the values of string expressions.
SELECT
a.AccountID,
a.Username,
a.LastNm + ', ' + a.FirstNm AS Name ,
a.Lastlogin,
a.email AS Email,
STRING_AGG(
( SELECT b.LastNm + ' ' + b.FirstNm
FROM
tblReviewers
INNER JOIN tblUserAccount b ON r.ReviewerID = b.AccountID
WHERE
r.AnalystID = a.AccountID ),
', ') AS ReviewerName
FROM
tblUserAccount a
This allows you to return more than one reviewer in one field.
I would like to create a table of job ids and a column listing all the different job categories that get matched up, but concatenated into the same column. As an example, right now job 82041 has two categories, but now is returning two rows. I would like for it to say "Retail, Sales Associate", all in one field.
The code that I tried is below, can anybody tell me what I am doing wrong?
EXAMPLE:
jobOrderID (No column name)
82027 Motion Graphics
82029 Other
82030 Product Designer
82041 Retail
82041 Sales Associate
82069 Social Media
EXAMPLE CODE:
select JobOrder.jobOrderID ,
stuff((select distinct ', ' + cast(Category.occupation as nchar(30))
from Category
where Category.categoryID = JobOrderCategories.categoryID
for xml path ('')),1,1,'')
from JobOrder
left outer join JobOrderCategories
on JobOrder.joborderid = JobOrderCategories.jobOrderID
left outer join Category
on Category.categoryID = JobOrderCategories.categoryID
where JobOrder.dateAdded > '2017-5-2' and JobOrder.dateAdded < '2017-5-3'
and joborder.isDeleted = 0
order by joborder.dateAdded asc
Figured it out by altering the left joins
select
JobOrder.jobOrderID,
stuff((select distinct ', ' + cast(Category.occupation as varchar(30))
from Category
left outer join JobOrderCategories on (Category.categoryID = JobOrderCategories.categoryID and joborder.jobOrderID = JobOrderCategories.joborderid)
where Category.categoryID = JobOrderCategories.categoryID
for xml path ('')),1,1,'')
from JobOrder
where JobOrder.dateAdded > '2017-5-2' and JobOrder.dateAdded < '2017-5-3'
and joborder.isDeleted = 0
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem β and include valid code to reproduce it β in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I have edited the SQL to use DISTINCT however I am still getting the same data as when I use GROUP BY. Any suggestions?
When I use GROUP BY it requires that all the fields in the select clause are included, can anyone tell me why that is?
Any help is greatly appreciated.
SELECT DISTINCT
TrnClaim.ClientID
, TrnClaim.FileNo
, TrnLegend.RecordNo
, RTRIM(dbo.TrnClient.ClientName + ' ' + ISNULL(dbo.TrnClient.Initials,'') + ' ' + (CASE WHEN dbo.TrnClient.LanguageCode = 'A' THEN ISNULL(dbo.TrnClient.Title, 'Mr') ELSE ISNULL(dbo.TrnClient.Title,'')END)) AS NameInitials
, TrnClient.IDNumber
, ISNULL(dbo.MstInsurer.InsurerName, 'Unknown') AS InsurerName
, CAST(dbo.TrnPolicy.AgentID AS VARCHAR(10)) + ' ' + ISNULL(CAST(dbo.MstAgent.AgentName AS VARCHAR(50)),'Unknown') AS AgentIDName
, CAST(dbo.TrnPolicy.TeamID AS VARCHAR(10)) + ' ' + ISNULL(dbo.VieTeamSelect.TeamName, 'Unknown') AS TeamIDName
, CAST(dbo.TrnPolicy.LinkID AS VARCHAR(10)) + ' ' + ISNULL(dbo.MstLink.LinkName, 'Unknown') AS LinkIDName
, CAST(dbo.TrnPolicy.SubagentID AS VARCHAR(10)) + ' ' + ISNULL(dbo.MstSubagent.SubagentName, 'Unknown') AS SubagentIDName
, CAST(dbo.TrnPolicy.MarketerID AS VARCHAR(10)) + ' ' + ISNULL(dbo.MstMarketerCodes.MarketerName, 'Unknown') AS MarketerIDName
, dbo.TrnRisk.RiskID
, dbo.TrnRisk.Registration
, dbo.TrnRisk.VehID
, dbo.TrnRisk.VinNo
, dbo.TrnRisk.VehMake
, dbo.TrnRisk.VehMake
, dbo.TrnRisk.VehModel
, dbo.TrnRisk.VehModel
, dbo.TrnExt.ExtStartDate
, dbo.TrnExt.ExtEndDate
, dbo.MstRateCodes.RateCodeID
, dbo.TrnExt.ExtDesc
, dbo.TrnPolicy.Status AS PolicyStatus
, dbo.TrnPolicy.PayMeth
, dbo.TrnPolicy.PolicyPeriod
, 1 AS [Count]
, dbo.TrnPolicy.TotalPrem AS LastMonthPremium
--, LastPolicy.TotalDue AS LastMonthTotalDue
, dbo.TrnPolicy.TeamID
, dbo.TrnPolicy.AgentID
, dbo.TrnPolicy.LinkID
, ISNULL(dbo.TrnPolicy.LeadInsurerID,MstInsurer.InsurerID) AS InsurerIDForFilter
, dbo.TrnLegend.LegendDescr
, dbo.TrnLegend.ActiveDate
FROM dbo.TrnClaim
INNER JOIN dbo.TrnPolicy ON
TrnClaim.ClientID = dbo.TrnPolicy.ClientID
AND
TrnClaim.FileNo = dbo.TrnPolicy.FileNo
INNER JOIN dbo.TrnClient ON
dbo.TrnPolicy.ClientID = dbo.TrnClient.ClientID
INNER JOIN dbo.TrnRisk ON
dbo.TrnPolicy.ClientID = dbo.TrnRisk.ClientID
AND
dbo.TrnPolicy.FileNo = dbo.TrnRisk.FileNo
INNER JOIN dbo.TrnExt ON
dbo.TrnRisk.ClientID = dbo.TrnExt.ClientID
AND
dbo.TrnRisk.FileNo = dbo.TrnExt.FileNo
LEFT OUTER JOIN dbo.MstRateCodes ON
dbo.MstRateCodes.RateCodeID = dbo.TrnExt.ExtCode
LEFT OUTER JOIN dbo.MstInsurer MstInsurerLead ON
dbo.TrnPolicy.LeadInsurerID = MstInsurerLead.InsurerID
LEFT OUTER JOIN dbo.TrnPolicy LastPolicy ON
dbo.TrnPolicy.ClientID = LastPolicy.ClientID
AND
dbo.TrnPolicy.FileNo = LastPolicy.FileNo
LEFT OUTER JOIN dbo.MstAgent ON
dbo.TrnPolicy.AgentID = dbo.MstAgent.AgentID
LEFT OUTER JOIN dbo.MstSubagent ON
dbo.TrnPolicy.SubagentID = dbo.MstSubagent.SubagentID
LEFT OUTER JOIN dbo.MstMarketerCodes ON
dbo.TrnPolicy.MarketerID = dbo.MstMarketerCodes.MarketerID
LEFT OUTER JOIN dbo.VieTeamSelect ON
dbo.TrnPolicy.TeamID = dbo.VieTeamSelect.TeamID
LEFT OUTER JOIN dbo.MstLink ON
dbo.TrnPolicy.LinkID = dbo.MstLink.LinkID
LEFT OUTER JOIN dbo.MstInsurer ON
dbo.MstInsurer.InsurerID= dbo.TrnClaim.InsurerID
INNER JOIN dbo.TrnLegend On
dbo.TrnLegend.ClientID = dbo.TrnClaim.ClientID
AND
dbo.TrnLegend.FileNo = dbo.TrnClaim.FileNo
WHERE
Upper(dbo.TrnLegend.LegendDescr) LIKE '%CANCELLED%'
Order By
dbo.TrnClaim.ClientID
, dbo.TrnClaim.FileNo
, dbo.TrnLegendRecordNo
When using Group By you specify list of attributes. A query that contains a GROUP BY clause generates one row per group based on each unique combination of values of the attributes that belong to the grouping set.
Consequently, when GROUP BY is specified in a query, all subsequent steps (HAVING, SELECT, and so on) can specify only expressions that have a scalar (singular) value per group. These expressions can include columns or expressions from the GROUP BY list like TrnClaim.ClientID βor aggregate functions, such as COUNT(TrnClaim.ClientID).
As I can see you have not included any aggregate function in your query above that's why when you write say Group By (TrnClaim.ClientID) or any other column then no group is created or to rephrase each row becomes a unique group and so it requires that all the fields in the select clause are included.
That's the reason why you are getting same data with Distinct and GROUP BY becuase no group has been created.