CASE statement in the ORDER BY CLAUSE - sql

SQL SERVER
I'm attempting to sort records in my ORDER BY clause in an exact manner. So the records should be sorted in the following manner. I think my issue might be the CASE STATEMENT syntax, but I can't seem to find anything telling me that it's wrong, other than the code not running.
od.Status
Firm,
In Process,
Released,
Everything Else
I believed I could assign each type of record a number, and then sort those numbers.
The code below gives me "ORDER BY items must appear in the select list if SELECT DISTINCT is specified"
SELECT DISTINCT
oh.Order_Number AS Order_Number,
oh.Status AS Order_Status,
oh.Customer_Name AS Customer_Name,
vsc.Salesman_Name AS Salesman_Name,
vsc.Email_Address AS Email_Address,
od.Work_Code AS Work_Code,
od.Product_Code AS Product_Code,
CONVERT(char(10),od.Projected_Ship_Date,101) AS Projected_Ship_Date,
CONVERT(char(10),od.Due_Date,101) AS OD_Due_Date,
format(oh.Gross_Amount, '$#,##0.##') AS Gross_Amount,
DATEDIFF(DAY,oh.Order_Date,'{%Current Date%}') AS DIP,
od.Part_Number AS Part_Number,
od.Status AS Status,
CAST(qd.Delivery_Notes AS NVARCHAR(MAX)) AS Delivery_Notes
FROM
dbo.Order_Header oh LEFT OUTER JOIN dbo.Commission_Distribution cd ON oh.Order_Header_ID = cd.Order_Header_ID LEFT OUTER JOIN
dbo.vSalesman_Code vsc ON cd.Salesman_Code = vsc.Salesman_Code JOIN
dbo.Order_Detail od ON od.Order_Header_ID = oh.Order_Header_ID JOIN
dbo.Quotation_Detail qd ON od.Quotation_Detail_ID = qd.Quotation_Detail_ID JOIN
dbo.Quotation_Header qh ON qd.Quotation_Header_ID = qh.Quotation_Header_ID
WHERE
oh.Status = 'Open' AND
cd.Company_Code = 'AIN' AND
oh.Customer_Name NOT IN ( 'A.I. Innovations' , 'AI PROPERTIES Fortville LLC' , 'AI-IN Intercompany' , 'AI-NC Intercompany' ) AND
od.Status <> 'Closed' AND
LEFT(od.Part_Number, 3) <> 'MTS' AND
vsc.Salesman_Name NOT IN ( 'House' , 'House Accounts' ) AND
od.Status <> 'Hold' AND
od.Product_Code NOT LIKE '%PROCES%' AND
od.Product_Code NOT LIKE '%VISTA WARRANT%'
ORDER BY
CASE
WHEN od.Status = 'Firm' THEN 1
WHEN od.Status = 'In Process' THEN 2
WHEN od.Status = 'Released' THEN 3
ELSE 4
END,
vsc.Email_Address ASC,
CONVERT(char(10),od.Projected_Ship_Date,101) ASC
Any help on this would be appreciated. I haven't been able to find very much on this issue. Most issues I've found want to sort one set DESC, and another set ASC, but not in a particular order.
Thanks

Just updated your query:
SELECT DISTINCT
oh.Order_Number AS Order_Number,
oh.Status AS Order_Status,
oh.Customer_Name AS Customer_Name,
vsc.Salesman_Name AS Salesman_Name,
vsc.Email_Address AS Email_Address,
od.Work_Code AS Work_Code,
od.Product_Code AS Product_Code,
CONVERT(char(10),od.Projected_Ship_Date,101) AS Projected_Ship_Date,
CONVERT(char(10),od.Due_Date,101) AS OD_Due_Date,
format(oh.Gross_Amount, '$#,##0.##') AS Gross_Amount,
DATEDIFF(DAY,oh.Order_Date,'{%Current Date%}') AS DIP,
od.Part_Number AS Part_Number,
od.Status AS Status,
CAST(qd.Delivery_Notes AS NVARCHAR(MAX)) AS Delivery_Notes,
CASE
WHEN od.Status = 'Firm' THEN 1
WHEN od.Status = 'In Process' THEN 2
WHEN od.Status = 'Released' THEN 3
ELSE 4
END As StatusOrderId
FROM
dbo.Order_Header oh LEFT OUTER JOIN dbo.Commission_Distribution cd ON
oh.Order_Header_ID = cd.Order_Header_ID LEFT OUTER JOIN
dbo.vSalesman_Code vsc ON cd.Salesman_Code = vsc.Salesman_Code JOIN
dbo.Order_Detail od ON od.Order_Header_ID = oh.Order_Header_ID JOIN
dbo.Quotation_Detail qd ON od.Quotation_Detail_ID = qd.Quotation_Detail_ID JOIN
dbo.Quotation_Header qh ON qd.Quotation_Header_ID = qh.Quotation_Header_ID
WHERE
oh.Status = 'Open' AND
cd.Company_Code = 'AIN' AND
oh.Customer_Name NOT IN ( 'A.I. Innovations' , 'AI PROPERTIES Fortville LLC' , 'AI-IN Intercompany' , 'AI-NC Intercompany' ) AND
od.Status <> 'Closed' AND
LEFT(od.Part_Number, 3) <> 'MTS' AND
vsc.Salesman_Name NOT IN ( 'House' , 'House Accounts' ) AND
od.Status <> 'Hold' AND
od.Product_Code NOT LIKE '%PROCES%' AND
od.Product_Code NOT LIKE '%VISTA WARRANT%'
ORDER BY
CASE
WHEN od.Status = 'Firm' THEN 1
WHEN od.Status = 'In Process' THEN 2
WHEN od.Status = 'Released' THEN 3
ELSE 4
END,
vsc.Email_Address ASC,
CONVERT(char(10),od.Projected_Ship_Date,101) ASC

The problem is that the "case" statement in your order by must actually appear as a column in the select statement because you are doing a select distinct. Here is an example, the first query is invalid, the second works
select distinct
tableName = t.name
from sys.tables t
order by case
when t.name like '%something%' then 1
else 2
end;
select distinct
orderingColumn = case
when t.name like '%something%' then 1
else 2
end,
tableName = t.name
from sys.tables t
order by case
when t.name like '%something%' then 1
else 2
end
The problem here is that the orderingColumn will be returned by the select statement, and it seems like you don't want that, but that's easily fixed by a CTE or subquery:
with MyQuery as
(
select distinct
orderingColumn = case
when t.name like '%something%' then 1
else 2
end,
tableName = t.name
from sys.tables t
)
select tableName from MyQuery order by orderingColumn;

Related

Joining multiple tables results in duplicate rows

There are tow tables (Customer & Feedback) that have different information. The following query is almost correct, except that it results in duplicate rows. I only need unique rows as par customerId and NO for null value.
I tried the GROUP BY clause at the end but it gives error.
Select C.CustomerId,
C.FirstName,
C.LastName,
(SELECT CAST(CASE WHEN F.Id != null or F.Type = 'Query'
THEN 'YES' ELSE 'NO' END AS NVARCHAR(50))) as Query,
(SELECT CAST(CASE WHEN F.Id != null or F.Type = 'Feedback'
THEN 'YES' ELSE 'NO' END AS NVARCHAR(50))) as Feedback
FROM Customer C
LEFT JOIN Feedback F on F.CustomerId= C.CustomerId
Select * from Customer
Select * from Feedback
As Result I want to display only single row by customerId and to join the feedback table data like below...
You May Try either of the Below
SELECT
C.*,
Query = CASE WHEN PVT.Query IS NOT NULL THEN 'Yes' ELSE 'No' END,
Feedback = CASE WHEN PVT.Feedback IS NOT NULL THEN 'Yes' ELSE 'No' END
FROM Customer C
LEFT JOIN FeedBack
PIVOT
(
MAX(Id)
FOR
[Type] IN
(
[Query],[Feedback]
)
)Pvt
ON PVT.CustomerId = c.CustomerId
or Simply
SELECT
C.*,
Query = CASE WHEN EXISTS(SELECT 1 FROM FeedBack WHERE CustomerId = C.CustomerId and [Type]='Query') THEN 'Yes' ELSE 'No' END,
Feedback = CASE WHEN EXISTS(SELECT 1 FROM FeedBack WHERE CustomerId = C.CustomerId and [Type]='Feedback') THEN 'Yes' ELSE 'No' END
FROM Customer C
To Make it more Dynamic ou may Try this
DECLARE #SQL VARCHAR(MAX)
;WITH CTE
AS
(
SELECT
RN = ROW_NUMBER() OVER(PARTITION BY [Type] ORDER BY [Type]),
QRY = LTRIM(RTRIM([Type]))+' = CASE WHEN EXISTS(SELECT 1 FROM FeedBack WHERE CustomerId = C.CustomerId and [Type]='''+LTRIM(RTRIM([Type]))+''') THEN ''Yes'' ELSE ''No'' END'
FROM FeedBack
)
SELECT
#SQL = 'SELECT
C.*'
+SUBSTRING(','+L.List,1,LEN(L.List)-1)
+' FROM Customer C'
FROM
(
SELECT
QRY + ', ' [text()]
FROM CTE
WHERE RN = 1
FOR XML PATH('')
)L(List)
EXEC(#SQL)
Please Refer this Sqlfiddle for detailed example
Select C.CustomerId,
C.FirstName,
C.LastName,
sum(case when F.Type = 'Query' then 1 else 0 end) > 0 as Query,
sum(case when F.Type = 'Feedback' then 1 else 0 end) > 0 as Feedback
FROM Customer C
LEFT JOIN Feedback F on F.CustomerId= C.CustomerId
GROUP BY C.CustomerId, C.FirstName, C.LastName
use case when
Select C.CustomerId,
C.FirstName,
C.LastName,
case when sum(case when F.Type = 'Query' then 1 else 0 end) > 0 then 'Yes' else 'NO' end as Query,
case when sum(case when F.Type = 'Feedback' then 1 else 0 end) > 0 then 'Yes' else 'NO' End as Feedback
FROM Customer C
LEFT JOIN Feedback F on F.CustomerId= C.CustomerId
GROUP BY C.CustomerId, C.FirstName, C.LastName
Try below query using subquery:
select *,case when query=1 then 'Yes' else 'No' end as query,
case when feedback=1 then 'Yes' else 'No' end as feedbackfrom
(select CustomerId, firstname,lastname,
sum(CASE WHEN Type = 'Query'
THEN 1 ELSE 0 END) as Query,
sum(CASE WHEN Type = 'Feedback'
THEN 1 ELSE 0 END) as Feedback from Customer C
LEFT JOIN Feedback F on F.CustomerId= C.CustomerId
group by CustomerId, firstname,lastname)a
Try this:
select c.CustomerId,
c.FirstName,
c.LastName,
case when q.CustomerId is null then 'NO' else 'YES' end Query,
case when f.CustomerId is null then 'NO' else 'YES' end Feedback,
from Customers c
left join (select customerId from Feedback where Type = 'Query' ) q on c.CustomerId = q.CustomerId
left join (select customerId from Feedback where Type = 'Feedback' ) f on c.CustomerId = q.CustomerId

SQl query optimzation

*can anyone help me optimizing the query. I am using this query in an ETL called streamsets and it is yielding 70 records for 6 minutes when i run an streamsets pipleline which is very slow.we are taking this query from an SSIS package and joining each of the tables using left outer joins.I need to optimize it so that it fetches atleast 1000 records per minute in streamsets *
SELECT [FR].[ORDER_ID]
, [FR].[FULFILLMENT_REQUEST_ID]
, [SR].[SCREENING_RESULT_ID]
, [AT].[AG_TASK_ID]
, [RCC].[RESULT_CRIM_CASE_ID]
, [RCC].[RESULT_CRIM_CHARGE_ID]
, [FR].[JURISDICTION_ID]
, [COUNTY] = CASE WHEN [FR].[PRODUCT_ID] = 2 THEN [JC].[COUNTY_NAME] ELSE '' END
, [STATE] = CASE WHEN [FR].[PRODUCT_ID] = 2 THEN [JC].[STATE_A2_CD] ELSE [JS].[STATE_A2_CD] END
, [JT].[JURISDICTION_TYPE_NAME]
, [FR].[PRODUCT_ID]
, [P].[PRODUCT_NAME]
, [FR].[ORGANIZATION_ID]
, [O].[ORGANIZATION_NAME]
, [SA].[SALARY_RANGE]
, [AGE] = YEAR(GETDATE()) - YEAR([FR].[SUBJECT_DOB])
, [FR].[SUBJECT_JOB_COUNTRY]
, [FR].[SUBJECT_JOB_STATE]
, [FR].[ENTRY_DATE]
, [FR].[CREATION_DATE]
, [FR].[CLOSED_DATE]
, [FR].[EXTERNAL_USER_ID]
, [FR].[GENDER_CODE_ID]
, [GC].[GENDER_CODE_VALUE]
, [AT].[DATA_SOURCE]
, [SU].[RESEARCHER_CLASS]
, [TT].[TASK_TYPE]
, [TT].[TASK_DESCRIPTION]
, [RCC].[CHARGE_DESCRIPTION]
, [RCC].[DISPOSITION_DESCRIPTION]
, [P].[GENERAL_LEDGER_NBR]
, [O].[SCHEME_AGENCY_ID]
, [RT].[RESULT_TYPE_ID]
, [RT].[RESULT_CATEGORY]
, [RT].[RESULT_TYPE]
, [SU].[USER_ID]
,FR.AG_STATUS_ID
, [SCREENING_REFERENCE_ID]=CAST(LEFT([FR].[SCREENING_REFERENCE_ID],250) AS VARCHAR(8000))
,[P1].POD_NAME
, ATH.AG_TASK_HISTORY_ID
,ATH.TASK_STATUS TASK_HISTORY_STATUS
, ATH.AG_TASK_DATE TASK_HISTORY_DATE
,[TT].[TASK_TYPE_ID]
,ATH.MODIFIED_BY_SYSTEM_USER_ID
,ATH.CF_SYSTEM_USER_ID
,'' AS [STATUS NOTES]
, FR.SCOPE_OF_SEARCH
, SR.COMMONNAMFLAG
,CASE WHEN SU.RESEARCHER_CLASS = 'EXTERNAL' THEN SU.[USER_ID] END AS VENDOR
, CASE [TT].TASK_TYPE_ID WHEN 14 THEN 'SD IN' WHEN 15 THEN 'MR' WHEN 1 THEN 'ER' END AS [REQUIRED_ACTION]
, CASE
WHEN [TT].TASK_TYPE_ID = 1 THEN
CASE ATH.TASK_STATUS
WHEN 'DOCUMENTUPLOADED' THEN 'FMT RECORD ENTRY'
WHEN 'ACKNOWLEDGED' THEN 'SEARCHES'
WHEN 'AWAITINGHITENTRY' THEN 'AWAITING HIT'
WHEN 'DISPUTE' THEN 'AWAITING HIT'
WHEN 'DOUBLEENTERRESULTS' THEN 'AWAITING HIT'
WHEN 'NEW' THEN 'SEARCHES'
WHEN 'SOURCEUNAVAILABLE' THEN 'SEARCHES'
WHEN 'UPLOADED' THEN 'SEARCHES'
END
WHEN [TT].TASK_TYPE_ID = 15 THEN
CASE ATH.TASK_STATUS
WHEN 'DISPUTE' THEN 'QC'
WHEN 'DOCUMENTUPLOADED' THEN 'QC'
WHEN 'DOUBLESMARTDATAREVIEW' THEN 'QC'
WHEN 'MANUALREVIEW' THEN 'QC'
END
WHEN [TT].TASK_TYPE_ID = 14 THEN
CASE ATH.TASK_STATUS
WHEN 'DISPUTE' THEN 'QC'
WHEN 'INFONEEDED' THEN 'QC'
WHEN 'INFOPROVIDED' THEN 'QC'
WHEN 'INFONEEDEDACK' THEN 'QC'
WHEN 'NEW' THEN 'QC'
WHEN 'SDINFONEEDED' THEN 'CD COMPLIANCE'
END
END AS [AOM STATUS]
, CASE
WHEN [TT].TASK_TYPE_ID = 1 AND
ATH.TASK_STATUS = 'DOCUMENTUPLOADED' AND
ATH.MODIFIED_BY_SYSTEM_USER_ID IS NOT NULL AND
ATH.CF_SYSTEM_USER_ID IS NOT NULL THEN 'ER DOCUMENT UPLOADED COMPLETE'
WHEN [TT].TASK_TYPE_ID = 14 AND
ATH.TASK_STATUS = 'INFONEEDED' THEN 'SD INFO NEEDED INFO NEEDED DATA'
WHEN [TT].TASK_TYPE_ID = 1 AND SU.RESEARCHER_CLASS = 'INTERNAL' AND
FR.AG_STATUS_ID NOT IN (152) THEN 'ER INTERNAL'
WHEN [TT].TASK_TYPE_ID = 1 AND
ATH.TASK_STATUS = 'AWAITINGHITENTRY' AND
ATH.MODIFIED_BY_SYSTEM_USER_ID IS NOT NULL AND
ATH.CF_SYSTEM_USER_ID IS NOT NULL AND
ATH.MODIFIED_BY_SYSTEM_USER_ID = ATH.CF_SYSTEM_USER_ID THEN 'ER AWAITING HIT ENTRY DATA'
WHEN [TT].TASK_TYPE_ID = 14 THEN 'SD INFO NEEDED DATA'
WHEN [TT].TASK_TYPE_ID = 15 AND
ATH.TASK_STATUS = 'INFONEEDED' THEN 'MR INFO NEEDED'
END AS AG_OPS_STATUS
, FR.EXTERNAL_ORDER_ID
, AOT.OTD
, drv_pod_name=[P1].POD_NAME
, TAT_IN_MIN= Case when TAT_IN_MIN < 0 then 0 else TAT_IN_MIN end
, SU2.USER_ID CF_SYS_USER
, SU3.USER_ID MODIFIED_SYS_USER
, GETDATE() GET_DATE
FROM AG_TASK_HISTORY [ATH] LEFT OUTER JOIN
(
(
(
(
(
(
(
(
(
SELECT [ORDER_ID] ,[FULFILLMENT_REQUEST_ID],[JURISDICTION_ID],[PRODUCT_ID],[ORGANIZATION_ID],[SUBJECT_DOB],[SUBJECT_JOB_COUNTRY],[SUBJECT_JOB_STATE],[ENTRY_DATE],[CREATION_DATE],[CLOSED_DATE],[EXTERNAL_USER_ID],[GENDER_CODE_ID],AG_STATUS_ID,[SCREENING_REFERENCE_ID],SCOPE_OF_SEARCH,EXTERNAL_ORDER_ID,POD_ID,[SALARY_RANGE_ID],[JURISDICTION_TYPE]
FROM [FULFILLMENT_REQUEST]
) FR
LEFT JOIN
(
(SELECT [SCREENING_RESULT_ID],[RESULT_TYPE_ID],[FULFILLMENT_REQUEST_ID],COMMONNAMFLAG FROM [SCREENING_RESULT] )[SR]
INNER JOIN [DBO].[RESULT_TYPE] [RT]
ON [RT].[RESULT_TYPE_ID] = [SR].[RESULT_TYPE_ID]
)
ON [SR].[FULFILLMENT_REQUEST_ID] = [FR].[FULFILLMENT_REQUEST_ID]
)
INNER JOIN [PRODUCT] [P]
ON [P].[PRODUCT_ID] = [FR].[PRODUCT_ID]
INNER JOIN [ORGANIZATION] [O]
ON [O].[ORGANIZATION_ID] = [FR].[ORGANIZATION_ID]
LEFT JOIN(
(SELECT [AG_TASK_ID],[DATA_SOURCE],[TASK_TYPE_ID],[FULFILLMENT_REQUEST_ID],[SYSTEM_USER_ID] FROM [AG_TASK] ) [AT]
INNER JOIN [TASK_TYPE] [TT]
ON [TT].[TASK_TYPE_ID] = [AT].[TASK_TYPE_ID]
)
ON [AT].[FULFILLMENT_REQUEST_ID] = [FR].[FULFILLMENT_REQUEST_ID])
LEFT OUTER JOIN (
(SELECT [RESULT_CRIM_CASE_ID],[SCREENING_RESULT_ID] FROM [RESULT_CRIM_CASE])[RC]
INNER JOIN (SELECT [RESULT_CRIM_CASE_ID],[RESULT_CRIM_CHARGE_ID],[CHARGE_DESCRIPTION],[DISPOSITION_DESCRIPTION] FROM [RESULT_CRIM_CHARGE]) [RCC]
ON [RCC].[RESULT_CRIM_CASE_ID] = [RC].[RESULT_CRIM_CASE_ID]
)
ON [SR].[SCREENING_RESULT_ID] = [RC].[SCREENING_RESULT_ID]
)
)
LEFT JOIN [SYSUSER] [SU]
ON [SU].[SYSTEM_USER_ID] = [AT].[SYSTEM_USER_ID]
LEFT OUTER JOIN [SALARY_RANGE] [SA]
ON [SA].[SALARY_RANGE_ID] = [FR].[SALARY_RANGE_ID]
)
LEFT OUTER JOIN [JURISDICTION_TYPE] [JT]
ON [JT].[JURISDICTION_TYPE_ID] = [FR].[JURISDICTION_TYPE]
)
LEFT OUTER JOIN [GENDER_CODE] [GC]
ON [GC].[GENDER_CODE] = [FR].[GENDER_CODE_ID]
)
LEFT OUTER JOIN [JURISDICTION_COUNTY] [JC]
ON [JC].[JURISDICTION_ID] = [FR].[JURISDICTION_ID]
LEFT OUTER JOIN [JURISDICTION_STATE] [JS]
ON [JS].[JURISDICTION_ID] = [FR].[JURISDICTION_ID]
)
ON [ATH].AG_TASK_ID=[AT].AG_TASK_ID
LEFT OUTER JOIN [POD] [P1] ON [FR].POD_ID = [P1].POD_ID
LEFT OUTER JOIN(
SELECT *, (DATEDIFF(MINUTE, [IN_DATE], [IP_DATE]))-(DATEDIFF(WK, [IN_DATE], [IP_DATE]) * (2*24*60))-
(CASE WHEN DATENAME(DW, [IN_DATE]) = 'SUNDAY'
THEN (24*60) ELSE 0 END)
-(CASE WHEN DATENAME(DW, [IP_DATE]) = 'SATURDAY'
THEN (24*60) ELSE 0 END) TAT_IN_MIN
FROM (
SELECT FULFILLMENT_REQUEST_ID , MAX([IN_DATE]) [IN_DATE], MAX([IP_DATE]) [IP_DATE]
FROM(
SELECT AG_TASK_HISTORY.FULFILLMENT_REQUEST_ID,
CASE WHEN (AG_TASK_HISTORY.TASK_STATUS='INFONEEDED' OR AG_TASK_HISTORY.TASK_STATUS='NEW') AND (SYSUSER.RESEARCHER_CLASS='EXTERNAL' OR SU1.RESEARCHER_CLASS ='EXTERNAL')
THEN AG_TASK_HISTORY.AG_TASK_DATE END [IN_DATE],
CASE WHEN (AG_TASK_HISTORY.TASK_STATUS='INFOPROVIDED' OR AG_TASK_HISTORY.TASK_STATUS='COMPLETE' OR AG_TASK_HISTORY.TASK_STATUS='DOCUMENTUPLOADED') AND (SYSUSER.RESEARCHER_CLASS='EXTERNAL' OR SU1.RESEARCHER_CLASS ='EXTERNAL')
THEN AG_TASK_HISTORY.AG_TASK_DATE END AS [IP_DATE]
FROM AG_TASK_HISTORY
LEFT JOIN SYSUSER(NOLOCK) ON AG_TASK_HISTORY.CF_SYSTEM_USER_ID = SYSUSER.SYSTEM_USER_ID
LEFT JOIN SYSUSER(NOLOCK) SU1 ON AG_TASK_HISTORY.MODIFIED_BY_SYSTEM_USER_ID = SU1.SYSTEM_USER_ID
WHERE AG_TASK_DATE >=CAST('01-JAN-'+CAST(YEAR(GETDATE())-3 AS CHAR(4))AS DATETIME)
) A GROUP BY FULFILLMENT_REQUEST_ID
)B
)AVT
ON FR.FULFILLMENT_REQUEST_ID = AVT.FULFILLMENT_REQUEST_ID
LEFT OUTER JOIN(
SELECT *, (DATEDIFF(DAY, [IN_DATE], [IP_DATE]))-
(DATEDIFF(WK, [IN_DATE], [IP_DATE]) * (2))-
(CASE WHEN DATENAME(DW, [IN_DATE]) = 'SUNDAY' THEN 1 ELSE 0 END)
-(CASE WHEN DATENAME(DW, [IP_DATE]) = 'SATURDAY' THEN 1 ELSE 0 END) OTD
FROM
(
SELECT FULFILLMENT_REQUEST_ID , MIN(CREATION_DATE) [IN_DATE], GETDATE() [IP_DATE]
FROM FULFILLMENT_REQUEST WHERE CLOSED_DATE IS NULL AND AG_STATUS_ID NOT IN (29,134,142,152)
GROUP BY FULFILLMENT_REQUEST_ID
)B
) AOT
ON FR.FULFILLMENT_REQUEST_ID = AOT.FULFILLMENT_REQUEST_ID
LEFT OUTER JOIN SYSUSER SU2
ON ATH.CF_SYSTEM_USER_ID=SU2.SYSTEM_USER_ID
LEFT OUTER JOIN SYSUSER SU3
ON ATH.MODIFIED_BY_SYSTEM_USER_ID=SU3.SYSTEM_USER_ID
WHERE SU.RESEARCHER_CLASS='EXTERNAL' AND (AVT.TAT_IN_MIN >0 OR AOT.[IP_DATE] IS NULL)
AND ATH.AG_Task_Date >=' 2017-07-07 09:02:23.050'
If you join tables and subselects you really have to know your indexes.
Use explain to check if there is a problem with using indexes.
It is possible that the query can't be optimized and has to be completely redesigned.
It's very hard to give you definite answer to your question because your query is huge and it will take long time to analyze it.
Here are some suggestions to you:
Get execution plan for it (copy it to SMSS and hit CTRL+L) that might give you suggestions what indexes are missing
Remove all the columns from the select list and leave just SELECT COUNT(*) FROM AG_TASK_HISTORY .... Check if you still have bad performance.
Then go from the bottom and eliminate join by join. After each elimination see if the performance is still bad.
After some eliminations you'll must probably get good time and that's means that you've found at least 1 bottleneck.
Then create a proper index for that and try again from step 2.
Other considerations would be to use stored procedures (if it possible) and split this big query into smaller parts, but I am pretty sure that with proper set of the indexes you can get much better performance than you have now.

Oracle Join - Which is faster - using the whole table or a subquery that has specific columns needed in the table?

I am really new into optimizing queries. Could you please advise which INNER JOIN runs faster?
Please note that i am using two different ways of inner join syntax(have same # of records)
1.) INNER JOIN of subqueries that have DISTINCT and selected columns only from its respective table
select
fac.fac_id ,
dept.dept_id ,
wk.week_id ,
sum(case when TRIM(fpl.MEASURE) like '%Salar%Wage%' then DATAVALUE else 0 end) WAGES_AMT,
sum(case when TRIM(fpl.MEASURE) like '%Tot%Man%hour%Ret%' then DATAVALUE else 0 end) MANHRS_QTY,
fpl.md_cycle_nbr ,
fpl.md_load_dt
from
EAS_STG.FPA_PLAN_LABOR fpl
INNER JOIN
(
select distinct(dept_nbr), dept_id
from department_D
where regexp_instr( Dept_nbr,'([^0-9])') = 0
) dept
ON TO_NUMBER(TRIM( 'D' FROM fpl.department)) = TO_NUMBER(dept.dept_nbr)
INNER JOIN
(
select distinct(FAC.FAC_NBR), fai.fac_id
from FACILITY_D fac, FACILITY_ALTERNATE_ID fai
where fac.fac_id = fai.fac_id
and fac.company_id = 1101
) fac
ON TRIM(REPLACE(fpl.facility, 'Fac-')) = fac.fac_nbr
INNER JOIN
(
select distinct(wk_hierarchy_id) week_id from DAY_HIERARCHY_D
) wk ON TO_NUMBER(TRIM(REPLACE(fpl.scenario, 'Plan ')) || TRIM(REPLACE(fpl.time, 'Wk '))) = WK.week_id
GROUP BY
fac.fac_id ,
dept.dept_id ,
wk.week_id ,
fpl.md_cycle_nbr ,
fpl.md_load_dt
;
2.) INNER JOIN of the whole table without the selected columns
SELECT fac.fac_id
, dept.dept_id
, d.wk_hierarchy_id week_id
, SUM(CASE WHEN TRIM(fpl.MEASURE) LIKE '%Salar%Wage%' THEN datavalue ELSE 0 END) WAGES_AMT
, SUM(CASE WHEN TRIM(fpl.MEASURE) LIKE '%Tot%Man%hour%Ret%' THEN datavalue ELSE 0 END) MANHRS_QTY
, fpl.md_cycle_nbr
, fpl.md_load_dt
FROM EAS_STG.FPA_PLAN_LABOR fpl
JOIN department_d dept
ON TO_NUMBER(TRIM( 'D' FROM fpl.department)) = TO_NUMBER(dept.dept_nbr)
JOIN facility_d fac
ON TRIM(REPLACE(fpl.facility, 'Fac-')) = fac.fac_nbr
JOIN facility_alternate_id fai
ON fac.fac_id = fai.fac_id
JOIN day_hierarchy_d d
ON TO_NUMBER(TRIM(REPLACE(fpl.scenario, 'Plan ')) || TRIM(REPLACE(fpl.time, 'Wk '))) = d.wk_hierarchy_id
WHERE fac.company_id = 1101
AND REGEXP_INSTR(dept_nbr,'([^0-9])') = 0
GROUP BY fac.fac_id
, dept.dept_id
, d.wk_hierarchy_id
, fpl.md_cycle_nbr
, fpl.md_load_dt
;

How do I compare SUM and COUNT()s in SQL?

I am building a small query to find all CustomerNumbers where all of their policies are in a certain status (terminated).
Here is the query I am working on
select
a.cn
,p.pn
, tp = COUNT(p.pn)
, tp2 = SUM(case when p.status = 4 then 1 else 0 end)
from
(
select cn, cn2
from bc
union
select cn, cn2= fn
from ic
) as a
left join p as p
on a.cn = p.cn
group by
a.cn,
pn
My issue is when I add the clause:
WHERE cn = tp
It says the columns are invalid. Am I missing something incredibly obvious?
You can't use aliases at the same level of a query. The reason is that the where clause is logically evaluated before the select, so the aliases defined in the select are not available in the where.
A typical solution is to repeat the expression (other answers) or use a subquery or cte:
with cte as (
<your query here>
)
select cte.*
from cte
where TotalPolicies = TermedPolicies;
However, in your case, you have an easier solution, because you have an aggregation query. So just use:
having TotalPolicies = TermedPolicies
You cannot use the aliased aggregate column names in the where clause. You have to use the expression itself instead. Also you cannot use it as where cluase, but use it in the having clause
HAVING COUNT(p.PolicyNumber) = SUM(case when p.status = 4 then 1 else 0 end)
You can also make the whole query as a subquery then add your where statement:
select CustomerNumber
,PolicyNumber
,TotalPolicies
,TermedPolicies
from (
select
a.CustomerNumber
,p.PolicyNumber
, TotalPolicies = COUNT(p.PolicyNumber)
, TermedPolicies = SUM(case when p.status = 4 then 1 else 0 end)
from
(
select CustomerNumber, CompanyName
from BusinessClients
union
select CustomerNumber, CompanyName = FullName
from IndividualClients
) as a
left join Policies as p
on a.CustomerNumber = p.CustomerNumber
group by
a.CustomerNumber,
PolicyNumber
) tb
where TotalPolicies = TermedPolicies
select
a.CustomerNumber
,p.PolicyNumber
, COUNT(p.PolicyNumber) as TotalPolicies
, SUM(case when p.status = 4 then 1 else 0 end) as TermedPolicies
from
(
select CustomerNumber, CompanyName
from BusinessClients
union
select CustomerNumber, CompanyName = FullName
from IndividualClients
) as a
left join Policies as p
on a.CustomerNumber = p.CustomerNumber
WHERE COUNT(p.PolicyNumber)= SUM(case when p.status = 4 then 1 else 0 end)
group by
a.CustomerNumber,
PolicyNumber
This should work. But it is not tested.
In order to filter by an aggregate function, you must include it in the HAVING clause, rather than the WHERE clause.
select
a.CustomerNumber
,p.PolicyNumber
, TotalPolicies = COUNT(p.PolicyNumber)
, TermedPolicies = SUM(case when p.status = 4 then 1 else 0 end)
from
(
select CustomerNumber, CompanyName
from BusinessClients
union
select CustomerNumber, CompanyName = FullName
from IndividualClients
) as a
left join Policies as p
on a.CustomerNumber = p.CustomerNumber
having COUNT(p.PolicyNumber) = SUM(case when p.status = 4 then 1 else 0 end)
group by
a.CustomerNumber,
PolicyNumber
The reason for this has to do with the way SQL engines evaluate queries. The contents of the WHERE clause are used to filter out rows before the aggregate functions are applied. If you could reference aggregate functions there, the engine would have to have some way to determine which predicates to apply before aggregation and which to apply after. The HAVING clause allows the engine to have a clear demarcation between the two: WHERE applies before aggregation and HAVING applies after aggregation.
When dealing with aggregations in a query that has grouping, you will need to use HAVING. This should work:
select
a.CustomerNumber
,p.PolicyNumber
, TotalPolicies = COUNT(p.PolicyNumber)
, TermedPolicies = SUM(case when p.status = 4 then 1 else 0 end)
from
(
select CustomerNumber, CompanyName
from BusinessClients
union
select CustomerNumber, CompanyName = FullName
from IndividualClients
) as a
left join Policies as p
on a.CustomerNumber = p.CustomerNumber
group by
a.CustomerNumber,
PolicyNumber
HAVING TermedPolicies = SUM(case when p.status = 4 then 1 else 0 end)

CASE Statement in query

I am trying to return a bunch of values in a table without causing "duplicate" outputs. I thought a CASE statement or derived table may help? Any input would be great.
Within the column Product_code there are the following values
(AFF,E,H,PD,PDM,PDRL,PDRM etc)
Here is my SQL:
SELECT DISTINCT
[Member Id] = c.master_customer_id,
[Full Name] = c.label_name,
[First Name] = c.first_name,
[Last Name] = c.last_name,
[Email] = ISNULL(c.primary_email_address,''),
[Annual Meeting] = MAX(ca.product_code)
CASE WHEN od.product_code IN (AFF,E,H,PD,PDM,PDRL,PDRM) then ??
--[Membership Type] = od.product_code
FROM order_detail od
INNER JOIN customer c
on c.master_customer_id = od.ship_master_customer_id
and c.sub_customer_id = od.ship_sub_customer_id
and od.subsystem = 'MBR'
INNER JOIN cus_activity ca
on ca.master_customer_id = c.master_customer_id
and ca.sub_customer_id = c.sub_customer_id
and ca.subsystem = 'MTG'
and ca.activity_subcode IN ('2012AM', '2011AM')
and ca.product_code IN ('2012AM','2011AM')
INNER JOIN cus_address caddr
on caddr.master_customer_id = c.master_customer_id
and caddr.sub_customer_id = c.sub_customer_id
INNER JOIN cus_address_detail caddrd
on caddrd.cus_address_id = caddr.cus_address_id
where c.customer_class_code NOT IN ('STAFF', 'TEST_MBR')
and c.customer_status_code = 'ACTIVE'
and c.primary_email_address IS NOT NULL
and ca.master_customer_id IN (select order_detail.ship_master_customer_id
from order_detail where order_detail.subsystem = 'MBR')
and caddrd.priority_seq = 0
and caddrd.address_status_code = 'GOOD'
and od.product_code in
( 'AFF','E','H', 'PD','PDM','PDRL','PDRM','PDRU','R',
'RM','RRL','RRM','RRU','S','SM','SRL','SRM','SRU','SU','SUM','SURL','SURM','SURU' )
and od.cycle_end_date >= '01/01/2011' and od.cycle_end_date <= '12/31/2012'
GROUP BY c.master_customer_id,c.label_name,
c.FIRST_NAME,c.LAST_NAME,c.primary_email_address,od.product_code,caddr.country_descr
order by c.master_customer_id
You are looking for a Cross-Tab result (also known as a Pivot table) based on a given customer. You want all possible membership status levels as a person could be multiple levels (per your example).
With the group by on the customer ID, everything will roll-up to the member. So, if there are multiple product codes, I have applied SUM() based on each individual "product_code" you wanted to consider.
Next, to help optimize your query, I would ensure your Order_Detail has an index on
( SubSystem, Product_Code, Cycle_End_Date, ship_master_customer_id )
I've slightly rewritten to better allow myself to follow what you were getting and the criteria related to each table. Hopefully it makes sense to what you started with.
SELECT
c.master_customer_id as [Member Id],
c.label_name as [Full Name],
c.first_name as [First Name],
c.last_name as [Last Name],
ISNULL(c.primary_email_address,'') as [Email],
MAX(ca.product_code) as [Annual Meeting],
SUM( CASE WHEN od.product_code = 'AFF' then 1 else 0 end ) as Membership_AFF,
SUM( CASE WHEN od.product_code = 'E' then 1 else 0 end ) as Membership_E,
SUM( CASE WHEN od.product_code = 'H' then 1 else 0 end ) as Membership_H,
SUM( CASE WHEN od.product_code = 'PD' then 1 else 0 end ) as Membership_PD,
SUM( CASE WHEN od.product_code = 'PDM' then 1 else 0 end ) as Membership_PDM,
SUM( CASE WHEN od.product_code = 'PDRL' then 1 else 0 end ) as Membership_PDRL,
SUM( CASE WHEN od.product_code = 'PDRM' then 1 else 0 end ) as Membership_PDRM
FROM
order_detail od
INNER JOIN customer c
on od.ship_master_customer_id = c.master_customer_id
and od.ship_sub_customer_id = c.sub_customer_id
and c.customer_class_code NOT IN ('STAFF', 'TEST_MBR')
and c.customer_status_code = 'ACTIVE'
and c.primary_email_address IS NOT NULL
INNER JOIN cus_activity ca
on od.ship_master_customer_id = ca.master_customer_id
and od.ship_sub_customer_id = ca.sub_customer_id
and ca.subsystem = 'MTG'
and ca.activity_subcode IN ('2012AM', '2011AM')
and ca.product_code IN ('2012AM','2011AM')
INNER JOIN cus_address caddr
on od.ship_master_customer_id = caddr.master_customer_id
and od.ship_sub_customer_id = caddr.sub_customer_id
INNER JOIN cus_address_detail caddrd
on caddr.cus_address_id = caddrd.cus_address_id
and caddrd.priority_seq = 0
and caddrd.address_status_code = 'GOOD'
WHERE
od.subsystem = 'MBR'
and od.product_code in ( 'AFF','E','H','PD','PDM','PDRL','PDRM','PDRU',
'R','RM','RRL','RRM','RRU','S','SM','SRL',
'SRM','SRU','SU','SUM','SURL','SURM','SURU' )
and od.cycle_end_date >= '01/01/2011'
and od.cycle_end_date <= '12/31/2012'
GROUP BY
od.ship_master_customer_id,
c.label_name,
c.FIRST_NAME,
c.LAST_NAME,
c.primary_email_address,
caddr.country_descr
order by
od.ship_master_customer_id