So here is the query code we are using:
SELECT
CONVERT(DATE, Nominations.Nomination_Date_Created) AS Nomination_Date_Created,
Nominations.Nomination_Status,
(CASE
WHEN MIN(EPORT.dbo.FDA_Divisions.division_name) = MAX(EPORT.dbo.FDA_Divisions.division_name)
THEN MIN(EPORT.dbo.FDA_Divisions.division_name)
ELSE 'Multiple Divisions'
END) AS Employee_Division,
Nominations.Nomination_Awarded_For,
Nominations.Nomination_Awarded_Other,
Nom.First_Name + ' ' + Nom.Last_Name AS Nominator_Name,
Nominations.Nomination_Group_UUID,
Nominations.Nomination_Group_Name,
Nominations.Nomination_Group_Time_off_Sum,
Nominations.Nomination_Group_Cash_Sum,
Nominations.Nomination_Type,
Nominations.Nomination_Identifier, Nominations.Nomination_Employee_UUID,
Nominations.Nomination_Nominator_ID, Nominations.Nomination_NOAC,
STUFF((SELECT ', ' + NOMGroup.division_name
FROM vw_group_nomination_divisions NOMGroup
WHERE NOMGroup.Nomination_Group_UUID = Nominations.Nomination_Group_UUID
FOR XML PATH('')), 1, 1, '') divList
FROM
Nominations
INNER JOIN
ePort.dbo.Employees AS Employees_1 ON Employees_1.CapHR_ID = Nominations.Nomination_Employee_CapHR_ID
LEFT OUTER JOIN
ePort.dbo.FDA_Offices ON Employees_1.office_id = ePort.dbo.FDA_Offices.office_id
LEFT OUTER JOIN
ePort.dbo.FDA_Centers ON Employees_1.center_ID = ePort.dbo.FDA_Centers.Center_ID
LEFT OUTER JOIN
ePort.dbo.FDA_Divisions ON Employees_1.division_id = ePort.dbo.FDA_Divisions.division_ID
LEFT OUTER JOIN
ePort.dbo.Employees AS Nom ON Nominations.Nomination_Nominator_ID = Nom.CapHR_ID
LEFT OUTER JOIN
ePort.dbo.Employees AS NomAppRTO ON Nominations.Nomination_Approving_Officer_NED_ID = NomAppRTO.CapHR_ID
GROUP BY
CONVERT(DATE, Nominations.Nomination_Date_Created),
Nominations.Nomination_Awarded_For, Nominations.Nomination_Status,
Nominations.Nomination_Awarded_Other,
Nom.First_Name + ' ' + Nom.Last_Name,
Nominations.Nomination_Type, Nominations.Nomination_Group_UUID,
Nominations.Nomination_Group_Name,
Nominations.Nomination_Group_Time_off_Sum,
Nominations.Nomination_Group_Cash_Sum,
Nominations.Nomination_Identifier, Nominations.Nomination_Type,
Nominations.Nomination_Employee_UUID,
Nominations.Nomination_Nominator_ID, Nominations.Nomination_NOAC
HAVING
(Nominations.Nomination_Type = 'Group')
AND (YEAR(CONVERT(DATE, Nominations.Nomination_Date_Created)) IN ('2020'))
ORDER BY
Nomination_Date_Created DESC, Nominations.Nomination_Group_UUID
Output:
| Id | divList |
+--------------------------------------+-------------------+
| 3462BF9B-5056-9C58-994BFFC6A38E7368 | DLR, DTD, OHCM |
| 3B8202C2-5056-9C58-99C591AA86B3A1C9 | OHCM |
| CB5A722C-5056-9C58-9983C1F6C66C0AD7 | DTD, STMD |
And the output is how we need it, however, we need to be able to search it and we cannot get that working. So how does one reference the column 'Name' that the Stuff function creates in the WHERE clause of the query?
We need to do a search within the HAVING OR WHERE clause for a value within the 'divList' column if possible. Such as divList IN ('OHCM').
Anytime I reference 'divList', I get the error:
Invalid column name 'divList'.
This would filter the results to records 1 and 2.
I hope that better explains it.
You don't want the string. Use more basic logic instead:
having sum(case when division_name = 'ccc' then 1 else 0 end) > 0
How is your temp table associated with the view. You need to join your temp table with the nominations view.
SELECT ID,
STUFF((SELECT ', ' + NOMGroup.division_name
FROM vw_group_nomination_divisions NOMGroup
WHERE NOMGroup.Nomination_Group_UUID = nom.Nomination_Group_UUID
FOR XML PATH('')), 1, 1, '') Name
FROM temp1
JOIN vw_group_nomination_divisions nom ON temp1.ID = nom.ID
WHERE Nominations.[Name] = 'ccc'
GROUP by ID
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 the following table relationships
Location.DeptFK
Dept.PK
Section.DeptFK
Subsection.SectionFK
Question.SubsectionFK
Answer.QuestionFK, SubmissionFK
Submission.PK, LocationFK
one query returns (MainTable)
QuestionNumberVar | Section | Subsection | Question | AnsYes | AnsNo | NA
1-1.1 Math Algebra Did you do your homework? 10 1 1
1-1.2 Math Algebra Did your dog eat it? 9 3 0
2-1.1 English Greek Did you do your homework? 8 0 4
The other returns (Query2)
Answer | Location | QuestionNumberVar | Critical
1 High 1-1.1 1
2 Middle 1-1.1 1
2 High 1-1.2 0
1 Middle 1-1.2 0
0 High 2-1.1 1
1 Elem 2-1.1 1
I want the (Query2) to return (IndividualTable)
QuestionNumberVar | Critical | High | Middle | Ele
1-1.1 1 1 2 'blank'
1-1.2 0 2 1 'blank'
2-1.1 1 0 'blank' 1
I then want to merge it on the end of the previous table using QuestionNumberVar as a key of sorts. so the table will look like
QuestionNumberVar | MainTable | IndividualTable
1-1.1 Data Data
1-1.2 Data Data
2-1.1 Data Data
Where the answers are grouped by QuestionNumberVar. The MainTable is not dynamic but the other IndividualTable needs to be dynamic. Location doesn't always appear for certain Dept's as seen at the relationships.
These Queries work for gathering the required Data but I don't know how to convert them to modify my tables how I would like. I think Pivot is what should be used for Query 2 to make IndividualTable I am also not sure how to mesh IndividualTable with MainTable
MainTable Query
SELECT Section.StepNumber + '-' + Question.QuestionNumber AS QuestionNumberVar,
Question.Question,
Subsection.Name AS Subsection,
Section.Name AS Section,
SUM(CASE WHEN (Answer.Answer = 0) THEN 1 ELSE 0 END) AS NA,
SUM(CASE WHEN (Answer.Answer = 1) THEN 1 ELSE 0 END) AS AnsNo,
SUM(CASE WHEN (Answer.Answer = 2) THEN 1 ELSE 0 END) AS AnsYes,
(select count(distinct Location.Abbreviation) from Department inner join Plant on location.DepartmentFK = Department.PK WHERE(Department.Name = 'insertParameter'))
as total
FROM Department inner join
section on Department.PK = section.DepartmentFK inner JOIN
subsection on Subsection.SectionFK = Section.PK INNER JOIN
question on Question.SubsectionFK = Subsection.PK INNER JOIN
Answer on Answer.QuestionFK = question.PK inner JOIN
Submission on Submission.PK = Answer.SubmissionFK inner join
Location on Location.DepartmentFK = Department.PK AND Location.pk = Submission.PlantFK
WHERE (Department.Name = 'InsertParameter') AND (Submission.MonthTested = '1/1/2017')
GROUP BY Question.Question, QuestionNumberVar, Subsection.Name, Section.Name, Section.StepNumber
ORDER BY QuestionNumberVar;
Query 2
SELECT Answer.Answer, Location.abbreviation, Section.StepNumber + '-' + Question.QuestionNumber AS QuestionNumber, Cast(Question.CriticalProcessVariable AS VARCHAR) AS CriticalProcessVariable
FROM Department left join
Section on Department.PK = Section.DepartmentFK left JOIN
Subsection on Subsection.SectionFK = Section.PK left JOIN
Question on Question.SubsectionFK = Subsection.PK left JOIN
Answer on Answer.QuestionFK = Question.PK left JOIN
Submission on Submission.PK = SubmissionFK left join
Location on Location.DepartmentFK = Department.PK AND Location.pk = Submission.PlantFK
WHERE (Department.Name = 'insertParameter') AND (Submission.MonthTested = '01/01/2017')
ORDER BY CAST(Section.StepNumber as INT) ASC, Question.QuestionNumber;
I have attempted to Pivot Query 2 to no avail. My problem always arises over not being able to sum by Answer because it doesn't recognize it (probably from not being in Location?) I am kind of lost as this is the most complex query I have ever made and I can't wrap my head around the requirements for Pivot and how to properly apply it.
Pivot was the way I handled this eventually working my way through error after error. T/SQL threw a few wrenches in my way. I first Pivoted Query 2
select #cols = STUFF((SELECT distinct ',' + QUOTENAME(PivotQ.Abbreviation)
from ( --QUERY2
) PivotQ
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT StepNumber + ''-'' + QuestionNum as QuestionNumber, '+#cols+' from
(
--Query2
) x
pivot
(
SUM(Answer)
for Abbreviation in (' + #cols + ')
) p
'
Then I used QuestionNumber as a Key to join to MainTable's QuestionNumber. I used a second #cols to make the columns for use in the second query
select #cols2 = STUFF((SELECT distinct ', PivotJoin.' + QUOTENAME(PivotQ.Abbreviation)
from ( --QUERY2
) PivotQ
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
'+ #cols2 +' --added into Select of MainTable
-- Added to From Statement
inner join
('+ #query +') PivotJoin on PivotJoin.QuestionNumber = Section.StepNumber + ''-'' + Question.QuestionNumber
I had to make The Pivot's Question Number the main because now that its T/SQL instead of pure SQL using the Alias in Group By no longer worked. I then added #cols2 to the Group By clause. and made it Order By PivotJoin.QuestionNumber instead.
------- id ------- id ------- id ------- id -------
| t-1 | <---> | t-a | <---> | t-b | <---> | s-a | <---> | s-b |
------- ------- ------- ------- -------
SELECT distinct
t-a.col, t-b.col
FROM
INNER JOIN t-1 ON t-1.id = t-a.id
LEFT OUTER JOIN t-b on t-a.id = t-b.id
GROUP BY
T-1.id
So what I want is to display a column from s-b (along with all the other columns being displayed) which is referenced by s-a which is referenced by t-b. I can display anything I want from t-a and t-b but I get errors trying to link up the other sub tables.
SELECT distinct
inspections.inspection_id as InspectionId,
convert(char(3),inspections.Inspection_Type) + ' ' + Inspection_Desc as Inspection,
inspections.current_status as Current_Status,
case when left(inspections.current_status,1) = 'X' then 'SCHEDULED' else inspection_status.status_description end as Current_Status_Name,
convert(varchar(10),max(distinct inspection_history.scheduled_date),101) as 'Last_Scheduled',
convert(varchar(10),max(distinct inspection_history.inspect_date),101) as 'Last_Inspected',
inspections.inspection_type,
case when (inspections.current_status <> 'A' and left(inspections.current_status,1) <> 'X' and left(inspections.current_status,1) <> 'S') then dbo.fn_DependencyCheckMessage(#PermitNum,inspections.inspection_type) else '' end as Dependency_Message,
case when (inspections.current_status <> 'A' and left(inspections.current_status,1) <> 'X' and left(inspections.current_status,1) <> 'S') and (dbo.fn_DependencyCheck(#PermitNum,inspections.inspection_type)=1 and dbo.fn_CheckTempDeposits(#PermitNum,inspections.inspection_type)=1 and dbo.fn_CertOccCheck(#PermitNum,inspections.inspection_type)=1) then 1 else 0 end as AllowSchedule,
inspection_comments.comment_description as comment
FROM inspections
inner join permit_arch on permit_arch.permit_id = Inspections.permit_id
inner join inspection_types on inspection_types.inspection_type = Inspections.inspection_type
LEFT OUTER JOIN inspection_history ON inspections.inspection_id = inspection_history.inspection_id
LEFT OUTER JOIN inspection_status ON inspections.current_status = inspection_status.status_code
LEFT JOIN inspection_history_comment ON inspection_history.insp_hist_id = inspection_history_comment.inspection_history_id
LEFT JOIN inspection_comments ON inspection_history_comment.comment_code = inspection_comments.comment_code
WHERE
permit_arch.permit_number = #PermitNum
AND
(inspection_types.internal_only is null or inspection_types.internal_only = 0)
AND
(inspection_history.status <> 'D' or inspection_history.status is null)
GROUP BY permit_arch.permit_number,permit_arch.permit_status, inspections.Inspection_Type, inspection_types.inspection_desc, inspections.current_status,inspection_status.status_description,
inspections.inspection_id
HAVING Permit_arch.permit_number = #Permitnum and (inspections.current_status <> 'D' or inspections.current_status is null) and inspections.inspection_type <> 34
ORDER BY inspections.inspection_type ASC
My joins are the last two. SSMS errors with:
Msg 8120, Level 16, State 1, Procedure procWebGetPermitInspectionsForSchedulingA, Line 20 [Batch Start Line 7]
Column 'inspection_comments.comment_description' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
Msg 145, Level 15, State 1, Procedure procWebGetPermitInspectionsForSchedulingA, Line 10 [Batch Start Line 7]
ORDER BY items must appear in the select list if SELECT DISTINCT is specified.
I want to get the column inspection_comments.description
You don't need group by in your query. It is used when there is an aggregated function like sum, max etc. in select statement. You also missed mentioning t-a before inner join in your query. I have included that in my query.
Also, Left outer join is nothing but Left join itself. Therefore, I changed that also in the query
Try this:-
SELECT distinct
t-a.col, t-b.col, s-b.col
FROM t-a
INNER JOIN t-1 ON t-1.id = t-a.id
LEFT JOIN t-b on t-a.id = t-b.id
LEFT JOIN s-a on t-b.id=s-a.id
LEFT JOIN s-b on s-a.id=s-b.id;
I am new to SQL and I don't know what's wrong in this query,
SELECT
wo.WORKORDERID "Request ID", (wo.CREATEDTIME) "Created on",
aau.FIRST_NAME "Requester", aac.EMAILID 'From',
[To] = STUFF((SELECT ', ' + Recipient_email
FROM workorder_recipients wor2
WHERE wor2.Workorderid = wor.Workorderid and wor2.To_cc_bcc='To'
FOR XML PATH('')), 1, 2, ''),
[CC] = STUFF((SELECT ', ' + Recipient_email
FROM workorder_recipients wor2
WHERE wor2.Workorderid = wor.Workorderid and wor2.To_cc_bcc='CC'
FOR XML PATH('')), 1, 2, ''),
cd.CATEGORYNAME "Category"
FROM
workorder_recipients wor
LEFT JOIN
workorder wo ON wor.workorderid = wo.workorderid
LEFT JOIN
ModeDefinition mdd ON wo.MODEID = mdd.MODEID
LEFT JOIN
SDUser sdu ON wo.REQUESTERID = sdu.USERID
LEFT JOIN
AaaUser aau ON sdu.USERID = aau.USER_ID
LEFT JOIN
SDUser crd ON wo.CREATEDBYID = crd.USERID
LEFT JOIN
AaaUser cri ON crd.USERID = cri.USER_ID
LEFT JOIN
AaaUserContactInfo aauc ON aau.USER_ID = aauc.USER_ID
LEFT JOIN
AaaContactInfo aac ON aauc.CONTACTINFO_ID = aac.CONTACTINFO_ID
LEFT JOIN
WorkOrderStates wos ON wo.WORKORDERID = wos.WORKORDERID
LEFT JOIN
CategoryDefinition cd ON wos.CATEGORYID = cd.CATEGORYID
WHERE
mdd.MODENAME = 'E-Mail'
AND cd.CATEGORYNAME in ('Agent Operational Technology (EMEA/UK/IE)','Client Technology')
AND wo.IS_CATALOG_TEMPLATE='0'
AND wo.CREATEDTIME >= 1416783600000
AND wo.CREATEDTIME <= 1417388399000
AND wo.ISPARENT='1'
GROUP BY
wo.workorderid
But I keep getting this error:
Column 'workorder_recipients.WORKORDERID' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
Thanks,
Atul
Imagine the following simple table (T) where ID is the primary key:
ID | Column1 | Column2 |
----|---------+----------|
1 | A | X |
2 | A | Y |
Then you write the following query
SELECT ID, Column1, Column2
FROM T
GROUP BY Column1;
This breaks the SQL Standard, and if it were to run without errors (which it would in MySQL), the result:
ID | Column1 | Column2 |
----|---------+----------|
1 | A | X |
Is no more or less correct than
ID | Column1 | Column2 |
----|---------+----------|
2 | A | Y |
So what you are saying is give me one row for each distinct value of Column1, which both results sets satisfy, so how do you know which one you will get? Well you don't.
For simplicity sake (and the way it is implemented in SQL Server) we state the rule that if an column is not contained in an aggregate function, it must be in the GROUP BY clause for it to appear in the select list. This is not strictly true, the SQL-Standard does allow columns in the select list not contained in the GROUP BY or an aggregate function, however these columns must be functionally dependent on a column in the GROUP BY. From the SQL-2003-Standard (5WD-02-Foundation-2003-09 - page 346) - http://www.wiscorp.com/sql_2003_standard.zip
15) If T is a grouped table, then let G be the set of grouping columns of T. In each contained
in , each column reference that references a column of T shall reference some column C that
is functionally dependent on G or shall be contained in an aggregated argument of a
whose aggregation query is QS.
For example, ID in the sample table is the PRIMARY KEY, so we know it is unique in the table, so the following query conforms to the SQL standard and would run in MySQL and fail in many DBMS currently (At the time of writing Postgresql is the closest DBMS I know of to correctly implementing the standard - Example here):
SELECT ID, Column1, Column2
FROM T
GROUP BY ID;
Since ID is unique for each row, there can only be one value of Column1 for each ID, one value of Column2 there is no ambiguity about
what to return for each row. As far as I know, Postgresql is the only DBMS that has gone anyway to implementing this.
In order for your query to work you would need to add some columns to the GROUP BY:
GROUP BY wo.workorderid, wo.CREATEDTIME, aau.FIRST_NAME, aac.EMAILID, cd.CATEGORYNAME
However, I think you can remove the issue of duplicates by removing workorder_recipients from your FROM, you don't appear to use this anywhere. Removing this reference should remove the need for GROUP BY
SELECT
[Request ID] = wo.WORKORDERID,
[Created on] = wo.CREATEDTIME,
[Requester] = aau.FIRST_NAME,
[From] = aac.EMAILID,
[To] = STUFF((SELECT ', ' + Recipient_email
FROM workorder_recipients wor2
WHERE wor2.Workorderid = wo.Workorderid
AND wor2.To_cc_bcc='To'
FOR XML PATH('')), 1, 2, ''),
[CC] = STUFF((SELECT ', ' + Recipient_email
FROM workorder_recipients wor2
WHERE wor2.Workorderid = wo.Workorderid
AND wor2.To_cc_bcc='CC'
FOR XML PATH('')), 1, 2, ''),
[Category] = cd.CATEGORYNAME
FROM workorder wo
LEFT JOIN ModeDefinition AS mdd
ON wo.MODEID = mdd.MODEID
LEFT JOIN SDUser AS sdu
ON wo.REQUESTERID = sdu.USERID
LEFT JOIN AaaUser AS aau
ON sdu.USERID = aau.USER_ID
LEFT JOIN SDUser AS crd
ON wo.CREATEDBYID = crd.USERID
LEFT JOIN AaaUser AS cri
ON crd.USERID = cri.USER_ID
LEFT JOIN AaaUserContactInfo AS aauc
ON aau.USER_ID = aauc.USER_ID
LEFT JOIN AaaContactInfo AS aac
ON aauc.CONTACTINFO_ID = aac.CONTACTINFO_ID
LEFT JOIN WorkOrderStates AS wos
ON wo.WORKORDERID = wos.WORKORDERID
LEFT JOIN CategoryDefinition AS cd
ON wos.CATEGORYID = cd.CATEGORYID
WHERE
mdd.MODENAME = 'E-Mail'
AND cd.CATEGORYNAME in ('Agent Operational Technology (EMEA/UK/IE)','Client Technology')
AND wo.IS_CATALOG_TEMPLATE='0'
AND wo.CREATEDTIME >= 1416783600000
AND wo.CREATEDTIME <= 1417388399000
AND wo.ISPARENT='1';
when you use GROUP BY in a query, you need to include every field in the group by which is in the select, except ones where you're aggregating - such as a SUM a MIN or a MAX (Amongst others).
So, to contrive an example, this would be invalid:
SELECT FirstName, LastName, SUM(Score)
FROM HighScores
GROUP BY FirstName
You would also need to include LastName in the GROUP BY to get the sum of a person's scores
For some reason, my query is returning dup rows. I am trying to create a SELECT DISTINCT query. Can someone please tell me what is wrong with my query?
SELECT DISTINCT
PT_AGCY_DTL.MLM_AGCY_NBR AS AgencyID
, AGENCY.ORG_NM AS Agency
, AGCY_ADDR.CTY_NM as AgencyCity
, AGCY_ADDR.ST_PRVN_CDE_CID as AgencyST
, AG_AGCY_CNTCT.AGCY_CNTCT_ID as ContactID
, AG_AGCY_CNTCT.CNTCT_DT AS ContactDt
, AG_AGCY_CNTCT.AGCY_RESULTS_TXT AS AgencyResults
, AG_AGCY_CNTCT.GEN_OVERVIEW_TXT AS GeneralOverview
, AG_AGCY_CNTCT.NB_RNWL_BUS_DISCUSSION_TXT AS NewAndRenewalBusinessDiscussions
, AG_AGCY_CNTCT.NB_RNWL_BUS_DISCUSSION_TXT AS NewAndRenewalBusinessDiscussions
, AG_AGCY_CNTCT.MKT_INTELLIGENCE_TXT AS MarketIntelligence
, AG_AGCY_CNTCT.AGCY_PERSONNEL_CHG_TXT AS AgencyPersonnelChanges
, AG_AGCY_CNTCT.MM_ISSUE_TXT AS MyMonitorIssues
, AG_AGCY_CNTCT.UW_CLM_ISSUE_TXT AS UnderwritingClaimIssues
, AG_AGCY_CNTCT.FOLLOW_UP_ITEM_TXT AS FollowUpActionItems
, AG_AGCY_CNTCT.NXT_CNTCT_DT AS NextScheduledVisitDate
, CONTACT_TYPE.CODE_NM AS ContactType
, CONVERT(VARCHAR, AG_AGCY_CNTCT.CNTCT_DT,101) + ' - ' + CONTACT_TYPE.CODE_NM AS ContactDtType
, AG_AGCY_CNTCT.CNTCT_DESC AS ContactDetails
, CASE
WHEN PRODUCER.LST_NM IS NULL THEN ' '
ELSE LTRIM(RTRIM(PRODUCER.FRST_NM)) + ' ' + LTRIM(RTRIM(PRODUCER.LST_NM)) END AS Producers
, CASE
WHEN MLM_EMPL.LST_NM IS NULL THEN ' '
ELSE LTRIM(RTRIM(MLM_EMPL.FRST_NM)) + ' ' + LTRIM(RTRIM(MLM_EMPL.LST_NM)) END AS Employees
, CASE
WHEN PROD_CAT.CODE_NM IS NULL THEN ' '
ELSE LTRIM(RTRIM(PROD_CAT.CODE_NM)) END AS ProductCategory
FROM
AG_AGCY_CNTCT
INNER JOIN PT_AGCY_DTL
ON AG_AGCY_CNTCT.AGCY_PID = PT_AGCY_DTL.PARTY_ID
INNER JOIN PT_PARTY AS AGENCY
ON AGENCY.PARTY_ID = AG_AGCY_CNTCT.AGCY_PID
LEFT OUTER JOIN PT_PARTY_ADDR AS AGCY_ADDR
ON AGCY_ADDR.PARTY_ID = AG_AGCY_CNTCT.AGCY_PID
INNER JOIN CD_CODE AS CONTACT_TYPE
ON CONTACT_TYPE.CODE_ID = AG_AGCY_CNTCT.CNTCT_TYP_CID
LEFT OUTER JOIN AG_AGCY_CNTCT_PRDCR_RLTNSHP
ON AG_AGCY_CNTCT_PRDCR_RLTNSHP.AGCY_CNTCT_ID = AG_AGCY_CNTCT.AGCY_CNTCT_ID
LEFT OUTER JOIN PT_PARTY AS PRODUCER
ON PRODUCER.PARTY_ID = AG_AGCY_CNTCT_PRDCR_RLTNSHP.PRDCR_PID
LEFT OUTER JOIN AG_AGCY_CNTCT_MLM_EMPL_RLTNSHP
ON AG_AGCY_CNTCT_MLM_EMPL_RLTNSHP.AGCY_CNTCT_ID = AG_AGCY_CNTCT.AGCY_CNTCT_ID
LEFT OUTER JOIN PT_PARTY AS MLM_EMPL
ON MLM_EMPL.PARTY_ID = AG_AGCY_CNTCT_MLM_EMPL_RLTNSHP.MLM_EMPL_PID
LEFT OUTER JOIN AG_AGCY_CNTCT_PROD_CAT_TYP_RLTNSHP
ON AG_AGCY_CNTCT_PROD_CAT_TYP_RLTNSHP.AGCY_CNTCT_ID = AG_AGCY_CNTCT.AGCY_CNTCT_ID
LEFT OUTER JOIN CD_CODE AS PROD_CAT
ON PROD_CAT.CODE_ID = AG_AGCY_CNTCT_PROD_CAT_TYP_RLTNSHP.PROD_CAT_TYP_CID
AND AGCY_ADDR.ADDR_TYP_CID = '30' -- business address
AND AGCY_ADDR.REC_STS_TYP_CID = 'A' -- active
WHERE
PT_AGCY_DTL.MLM_AGCY_NBR ='4759' --#AgencyID (this is the FILTER)
ORDER BY ContactDt DESC, ContactID DESC
You don't specify, but I suspect you are under the impression that the following rows are duplicate:
t1.col1 | t1.col2 | t2.col1
--------------------------------
1 | 1 | 1
1 | 1 | 2
This is not the case. As was mentioned in the comments, DISTINCT is applied to all columns you are selecting. You can see there are two different combinations of values, hence two rows will be returned. Some people will use an aggregate function and a group by to get around this. Example:
SELECT t1.col1, t1.col2, MAX(t2.col1)
FROM table1 t1
INNER JOIN table2 t2
on t1.whatever = t2.whatever
GROUP BY t1.col1, t1.col2
This would only return the second row. If you are doing this be sure that you understand that you are excluding information in order to force the appearance of a distinct set of records.