can we use order by after where clause in subquery? - sql

I am trying to sort the record on milestone id coloumn but it is throwing error at order by in subquery giving error as "The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP or FOR XML is also specified."
CREATE PROCEDURE [dbo].[spGetALLStudyCodedtls]
(
#StudyCodeId VARCHAR(MAX)
)
AS
BEGIN
SELECT X.[IsActive]
--scd.[StudyCodeId]
,
X.[StudyCode],
X.[ProductName],
X.[TherapyName],
X.[Dosage],
X.[StudyType],
X.[Condition],
X.[CountryName],
X.[CRO],
X.[Design],
X.[DesignTag],
X.[RnD ProjManager],
X.[Project Manager],
X.[IPDFillingTimeline],
X.[Comments],
X.[MileStoneId],
X.[Milestone],
X.[Category],
X.[BaseLineDate],
X.[ActualDate]
FROM (
SELECT sc.IsActive
--scd.[StudyCodeId]
,
scd.[StudyCode],
pm.ProductName,
tm.TherapyName,
dm.Dosage,
stm.StudyType,
com.Condition,
cn.CountryName,
crm.CRO,
dsm.Design,
dtm.DesignTag,
ud.[user_name] AS 'RnD ProjManager',
udd.[user_name] AS 'Project Manager',
scd.[IPDFillingTimeline],
scd.[Remarks] AS 'Comments',
mm.MileStoneId,
mm.MileStoneName AS 'Milestone',
mm.Category AS 'Category',
sc.[BaseLineDate],
sc.[ActualDate]
FROM [PMS].[dbo].[StudyCodeDetails] scd
INNER JOIN [dbo].[StudyCodeToMileStone] sc ON scd.StudyCodeId = sc.StudyCodeId
INNER JOIN [dbo].[MileStoneMaster] mm ON sc.MileStoneId = mm.MileStoneId
INNER JOIN dbo.ProductMaster pm ON scd.ProductId = pm.ProductId
INNER JOIN dbo.TherapyMaster tm ON tm.TherapyId = scd.TherapyId
INNER JOIN dbo.DosageMaster dm ON dm.DosageId = scd.DosageId
INNER JOIN dbo.CountryMaster cn ON cn.CountryId = scd.CountryId
INNER JOIN dbo.[User_Dtls] ud ON ud.Pk_ID = scd.RnDProjManagerId
INNER JOIN dbo.[User_Dtls] udd ON udd.Pk_ID = scd.ProjectManagerId
INNER JOIN dbo.CroMaster crm ON crm.CroId = scd.CRO
INNER JOIN dbo.DesignMaster dsm ON dsm.DesignId = scd.DesignId
INNER JOIN dbo.DesignTagMaster dtm ON dtm.DesignTagId = scd.DesignTagId
INNER JOIN dbo.StudyTypeMaster stm ON stm.StudyTypeId = scd.StudyTypeId
INNER JOIN dbo.ConditionMaster com ON com.ConditionId = scd.Condition
WHERE scd.StudyCodeId IN (
SELECT CAST(Item AS INTEGER)
FROM [dbo].[SplitString](#StudyCodeId, ',')
)
AND mm.[AdditionalPayment] = 0
ORDER BY mm.MileStoneId
) AS X
GROUP BY X.[IsActive]
--scd.[StudyCodeId]
,
X.[StudyCode],
X.[ProductName],
X.[TherapyName],
X.[Dosage],
X.[StudyType],
X.[Condition],
X.[CountryName],
X.[CRO],
X.[Design],
X.[DesignTag],
X.[RnD ProjManager],
X.[Project Manager],
X.[IPDFillingTimeline],
X.[Comments],
X.[MileStoneId],
X.[Milestone],
X.[Category],
X.[BaseLineDate],
X.[ActualDate]
END

Please try this one:
CREATE PROCEDURE [dbo].[spGetALLStudyCodedtls]
(
#StudyCodeId VARCHAR(MAX)
)
AS
BEGIN
SELECT X.[IsActive]
--scd.[StudyCodeId]
,
X.[StudyCode],
X.[ProductName],
X.[TherapyName],
X.[Dosage],
X.[StudyType],
X.[Condition],
X.[CountryName],
X.[CRO],
X.[Design],
X.[DesignTag],
X.[RnD ProjManager],
X.[Project Manager],
X.[IPDFillingTimeline],
X.[Comments],
X.[MileStoneId],
X.[Milestone],
X.[Category],
X.[BaseLineDate],
X.[ActualDate]
FROM (
SELECT t1.IsActive,
t1.[StudyCode],
t2.ProductName,
t2.TherapyName,
t2.Dosage,
t2.StudyType,
t2.Condition,
t2.CountryName,
t2.CRO,
t2.Design,
t2.DesignTag,
t2.[user_name] AS 'RnD ProjManager',
t2.[user_name] AS 'Project Manager',
t1.[IPDFillingTimeline],
scd.[Remarks] AS 'Comments',
t2.MileStoneId,
t2.MileStoneName AS 'Milestone',
t2.Category AS 'Category',
t1.[BaseLineDate],
t1.[ActualDate]
FROM
(
SELECT sc.IsActive,
scd.[StudyCode],
scd.[IPDFillingTimeline],
scd.[Remarks] AS 'Comments',
sc.[BaseLineDate],
sc.[ActualDate],
sc.MileStoneId
FROM [PMS].[dbo].[StudyCodeDetails] scd
INNER JOIN [dbo].[StudyCodeToMileStone] sc
ON scd.StudyCodeId = sc.StudyCodeId
) AS t1
CROSS APPLY (
SELECT pm.ProductName,
tm.TherapyName,
dm.Dosage,
stm.StudyType,
com.Condition,
cn.CountryName,
crm.CRO,
dsm.Design,
dtm.DesignTag,
ud.[user_name] AS 'RnD ProjManager',
udd.[user_name] AS 'Project Manager',
mm.MileStoneId,
mm.MileStoneName AS 'Milestone',
mm.Category AS 'Category',
FROM [dbo].[MileStoneMaster] mm
INNER JOIN dbo.ProductMaster pm ON scd.ProductId = pm.ProductId
INNER JOIN dbo.TherapyMaster tm ON tm.TherapyId = scd.TherapyId
INNER JOIN dbo.DosageMaster dm ON dm.DosageId = scd.DosageId
INNER JOIN dbo.CountryMaster cn ON cn.CountryId = scd.CountryId
INNER JOIN dbo.[User_Dtls] ud ON ud.Pk_ID = scd.RnDProjManagerId
INNER JOIN dbo.[User_Dtls] udd ON udd.Pk_ID = scd.ProjectManagerId
INNER JOIN dbo.CroMaster crm ON crm.CroId = scd.CRO
INNER JOIN dbo.DesignMaster dsm ON dsm.DesignId = scd.DesignId
INNER JOIN dbo.DesignTagMaster dtm ON dtm.DesignTagId = scd.DesignTagId
INNER JOIN dbo.StudyTypeMaster stm ON stm.StudyTypeId = scd.StudyTypeId
INNER JOIN dbo.ConditionMaster com ON com.ConditionId = scd.Condition
WHERE scd.StudyCodeId IN (
SELECT CAST(Item AS INTEGER)
FROM [dbo].[SplitString](#StudyCodeId, ',')
)
AND mm.[AdditionalPayment] = 0
AND mm.MileStoneId = t1.MileStoneId
ORDER BY mm.MileStoneId
) AS t2
) AS X
GROUP BY X.[IsActive]
--scd.[StudyCodeId]
,
X.[StudyCode],
X.[ProductName],
X.[TherapyName],
X.[Dosage],
X.[StudyType],
X.[Condition],
X.[CountryName],
X.[CRO],
X.[Design],
X.[DesignTag],
X.[RnD ProjManager],
X.[Project Manager],
X.[IPDFillingTimeline],
X.[Comments],
X.[MileStoneId],
X.[Milestone],
X.[Category],
X.[BaseLineDate],
X.[ActualDate]
END

Related

Optimizing Multiple SQL Queries

I have 2 queries that I want to optimize but I don't know how. The execution time is not acceptable for me.
I'm working with jira database and did query to show different tasks with some attributes.
The code is:
SET NOCOUNT ON
DROP TABLE IF EXISTS #TT
DROP TABLE IF EXISTS #TT1
DROP TABLE IF EXISTS #TT2
SELECT DISTINCT concat(pr.[pkey], '-', ji.[issuenum]) AS 'Ключ'
,concat('https://sd.finam.ru/browse/', pr.[pkey], '-', ji.[issuenum]) AS 'Ссылка'
,p.[pname] AS 'П'
,users.[display_name] AS 'Исполнитель'
,CAST(ji.[CREATED] AS smalldatetime) AS 'Создан'
,CAST(ji.[RESOLUTIONDATE] AS smalldatetime) AS 'Дата резолюции'
,ji.[issuenum]
INTO #TT
FROM
[jiraissue] AS ji
LEFT OUTER JOIN [changegroup] AS cg ON (cg.[issueid] = ji.[id])
LEFT OUTER JOIN [changeitem] AS ci ON (ci.[groupid] = cg.[id]) AND ci.FIELDTYPE='jira' AND ci.FIELD='status'
LEFT OUTER JOIN [app_user] AS au ON (au.[user_key] = cg.[AUTHOR])
LEFT OUTER JOIN [issuetype] AS itype ON (itype.[ID] = ji.[issuetype])
LEFT OUTER JOIN [priority] AS p ON (p.[ID] = ji.[PRIORITY])
LEFT OUTER JOIN [project] AS pr ON (pr.[ID] = ji.[PROJECT])
LEFT OUTER JOIN [cwd_user] as users ON (users.[user_name] = ji.[ASSIGNEE])
WHERE cg.[CREATED] >= CONVERT(datetime, '2021-12-01') AND cg.[CREATED] <= CONVERT(datetime, '2022-01-01') and CONVERT(NVARCHAR(MAX), ci.[NEWSTRING]) = N'Done'
AND itype.pname = 'Incident'
SELECT DISTINCT concat(pr.[pkey], '-', ji.[issuenum]) AS 'Ключ'
,system_t.[NAME] AS 'Контур ИС'
,system_t_t.[NAME] AS 'Критичность системы'
INTO #TT1
FROM
[jiraissue] AS ji
LEFT OUTER JOIN [changegroup] AS cg ON (cg.[issueid] = ji.[id])
LEFT OUTER JOIN [changeitem] AS ci ON (ci.[groupid] = cg.[id]) AND ci.FIELDTYPE='jira' AND ci.FIELD='status'
LEFT OUTER JOIN [app_user] AS au ON (au.[user_key] = cg.[AUTHOR])
LEFT OUTER JOIN [issuetype] AS itype ON (itype.[ID] = ji.[issuetype])
LEFT OUTER JOIN [project] AS pr ON (pr.[ID] = ji.[PROJECT])
LEFT OUTER JOIN [customfieldvalue] AS customfv ON (customfv.[ISSUE] = ji.[ID])
LEFT OUTER JOIN [AO_8542F1_IFJ_OBJ] AS system_t ON (system_t.[ID] = substring(customfv.[STRINGVALUE], PatIndex('%[0-9]%', customfv.[STRINGVALUE]), len(customfv.[STRINGVALUE])))
LEFT OUTER JOIN [AO_8542F1_IFJ_OBJ_ATTR] AS system_attr ON (system_t.[ID] = system_attr.[OBJECT_ID])
LEFT OUTER JOIN [AO_8542F1_IFJ_OBJ_ATTR_VAL] AS system_attr_val ON (system_attr.[ID] = system_attr_val.[OBJECT_ATTRIBUTE_ID])
LEFT OUTER JOIN [AO_8542F1_IFJ_OBJ] AS system_t_t ON (system_attr_val.[REFERENCED_OBJECT_ID] = system_t_t.[ID])
WHERE cg.[CREATED] >= CONVERT(datetime, '2021-12-01') AND cg.[CREATED] <= CONVERT(datetime, '2022-01-01') and CONVERT(NVARCHAR(MAX), ci.[NEWSTRING]) = N'Done'
AND (customfv.[CUSTOMFIELD] = 21003 OR customfv.[CUSTOMFIELD] = 21005)
AND (system_t.[OBJECT_TYPE_ID] = 136 OR system_t.[OBJECT_TYPE_ID] = 303 OR system_t.[OBJECT_TYPE_ID] = 143)
AND system_attr.[OBJECT_TYPE_ATTRIBUTE_ID] = 461
AND itype.pname = 'Incident'
SELECT ji.[issuenum]
,pr_pr.[pname] AS '(project) Project'
INTO #TT2
FROM
[jiraissue] AS ji
LEFT OUTER JOIN [customfieldvalue] AS customfv ON (customfv.[ISSUE] = ji.[ID])
LEFT OUTER JOIN [project] AS pr_pr ON (pr_pr.[ID] = CAST(customfv.[NUMBERVALUE] AS BIGINT))
LEFT OUTER JOIN [changegroup] AS cg ON (cg.[issueid] = ji.[id])
LEFT OUTER JOIN [changeitem] AS ci ON (ci.[groupid] = cg.[id]) AND ci.FIELDTYPE='jira' AND ci.FIELD='status'
LEFT OUTER JOIN [app_user] AS au ON (au.[user_key] = cg.[AUTHOR])
LEFT OUTER JOIN [issuetype] AS itype ON (itype.[ID] = ji.[issuetype])
WHERE cg.[CREATED] >= CONVERT(datetime, '2021-12-01') AND cg.[CREATED] <= CONVERT(datetime, '2022-01-01') and CONVERT(NVARCHAR(MAX), ci.[NEWSTRING]) = N'Done'
AND pr_pr.[pname] is not NULL
SELECT CTE.[Ключ], CTE.[Ссылка], CTE.[П], CTE.[Исполнитель], CTE.[Создан], CTE.[Дата резолюции], CTE2.[(project) Project], CTE1.[Контур ИС], CTE1.[Критичность системы], CTE.[issuenum]
FROM #TT CTE
LEFT OUTER JOIN #TT1 CTE1 ON (CTE1.[Ключ] = CTE.[Ключ])
LEFT OUTER JOIN #TT2 CTE2 ON (CTE2.[issuenum] = CTE.[issuenum])
DROP TABLE IF EXISTS #TT
DROP TABLE IF EXISTS #TT1
DROP TABLE IF EXISTS #TT2
There will be some information for the month before last.
summary of query
The next query is:
WITH CTE AS (
SELECT concat(p.pkey,'-',i.issuenum) AS 'Ключ',
cf.cfname,
cv.textvalue,
ROW_NUMBER() OVER (PARTITION BY i.issuenum ORDER BY i.issuenum) AS RowNumber_SLA
FROM customfield cf,
customfieldvalue cv,
jiraissue i,
project p
WHERE i.project = p.id
AND cv.issue = i.id
AND cv.customfield = cf.id
AND cf.customfieldtypekey = 'com.atlassian.servicedesk:sd-sla-field'
and i.issuenum IN ()
and CHARINDEX('"succeeded":false', TEXTVALUE) >0
)
SELECT CTE.Ключ
FROM CTE
WHERE RowNumber_SLA = 1
The goal is to get tasks where SLA has been failed.
So in and i.issuenum IN () my Python script is putting issue numbers that I got through previous query.
The average execution time is 3 minutes.
So, I want optimize this too, maybe join first query.
Sorry for my English. I'm not an English-speaking person.
P. S. Changing CONVERT(NVARCHAR(MAX), ci.[NEWSTRING]) = N'Done' to ci.[NEWSTRING] = 'Done' causing the error The data types ntext and varchar are incompatible in the equal to operator. Workaround - ci.[NEWSTRING] LIKE 'Done' fixing this.
The first query must be rewrite as :
SELECT DISTINCT
concat(pr.[pkey], '-', ji.[issuenum]) AS 'Ключ',
concat('https://sd.finam.ru/browse/', pr.[pkey], '-', ji.[issuenum]) AS 'Ссылка',
p.[pname] AS 'П',
users.[display_name] AS 'Исполнитель',
CAST(ji.[CREATED] AS SMALLDATETIME) AS 'Создан',
CAST(ji.[RESOLUTIONDATE] AS SMALLDATETIME) AS 'Дата резолюции',
ji.[issuenum]
INTO #TT
FROM [jiraissue] AS ji
INNER JOIN [changegroup] AS cg ON(cg.[issueid] = ji.[id])
INNER JOIN [changeitem] AS ci ON(ci.[groupid] = cg.[id])
AND ci.FIELDTYPE = 'jira'
AND ci.FIELD = 'status'
LEFT OUTER JOIN [app_user] AS au ON(au.[user_key] = cg.[AUTHOR])
INNER JOIN [issuetype] AS itype ON(itype.[ID] = ji.[issuetype])
LEFT OUTER JOIN [priority] AS p ON(p.[ID] = ji.[PRIORITY])
LEFT OUTER JOIN [project] AS pr ON(pr.[ID] = ji.[PROJECT])
LEFT OUTER JOIN [cwd_user] AS users ON(users.[user_name] = ji.[ASSIGNEE])
WHERE cg.[CREATED] >= CONVERT(DATETIME, '2021-12-01')
AND cg.[CREATED] <= CONVERT(DATETIME, '2022-01-01')
AND ci.[NEWSTRING] = 'Done'
AND itype.pname = 'Incident';
False outer joins are converted in INNER and I have aslo eliminate the ugly CONVERT to NVARCHAR(max)
Same troubles appears in the second query...

using CTE while declaring variables in SQL

I have two decraed variables and I am trying to set the values from the result of my CTE,
declare #Total_new_claims_received int
declare #Total_Claims_Processed int
End solution I'm looking for is being able to set both declared values from CTE results:
select #Total_new_claims_received = count(id)
from cte
where benefit_code_id not in ('739')
select #Total_Claims_Processed = count(id)
from cte2
where benefit_code_id not in ('739')
Current Code:
declare #Total_new_claims_received int
declare #Total_Claims_Processed int
with cte (ID, Date)
as (
select c.id, c.date
from axiscore.dbo.claim c with (nolock)
inner join claim_line cl on c.Claim_ID = cl.Claim_ID and cl.Linenum = 1
left join axiscore.dbo.member_policy mp with (nolock) on c.Member_Policy_ID = mp.Member_Policy_ID
left join axiscore.dbo.policy p with (nolock) on mp.policy_id = p.policy_id
inner join axiscore.dbo.Claim_Status s with (nolock) on c.Claim_Status_ID = s.Claim_Status_ID
left outer join axiscore.dbo.Claim_Reason_Type r with (nolock) on c.Claim_Reason_Type_ID = r.Claim_Reason_Type_ID
where
c.Updated_Date between '10-1-2019' and '10-31-2019'
and p.Payor_ID = 8
and (c.Claim_Status_ID <> 8)),
cte2 (ID, Date)
as
(
select c.id, c.date
from axiscore.dbo.claim c with (nolock)
inner join claim_line cl on c.Claim_ID = cl.Claim_ID and cl.Linenum = 1
left join axiscore.dbo.member_policy mp with (nolock) on c.Member_Policy_ID = mp.Member_Policy_ID
left join axiscore.dbo.policy p with (nolock) on mp.policy_id = p.policy_id
inner join axiscore.dbo.Claim_Status s with (nolock) on c.Claim_Status_ID = s.Claim_Status_ID
left outer join axiscore.dbo.Claim_Reason_Type r with (nolock) on c.Claim_Reason_Type_ID = r.Claim_Reason_Type_ID
where
c.Updated_Date between '10-1-2019' and '10-31-2019'
and p.Payor_ID = 8
and (c.Claim_Status_ID in (7,6))
and (c.Claim_Reason_Type_ID not in (136,137)))
select #Total_new_claims_received = count(id)
from cte
where benefit_code_id not in ('739')
select #Total_Claims_Processed = count(id)
from cte2
where benefit_code_id not in ('739')
Currently,
it's only setting the value for Total_new_claims_received. It errors out on the second select when I'm setting the value for Total_Claims_Processed. The error is 'invalid object name 'cte2'.
I'm using CTE instead of temp tables becuase I'm calling this proc in a SSIS package. SSIS package doesn't do well with Temp tables. Any other ideas welcome as well.
thanks for your time!
From WITH common_table_expression (Transact-SQL):
A CTE must be followed by a single SELECT, INSERT, UPDATE, or
DELETE statement that references some or all the CTE columns
So define each of your CTEs before each of the select statements that uses it:
declare #Total_new_claims_received int
declare #Total_Claims_Processed int
with cte (ID, Date) as (
select c.id, c.date
from axiscore.dbo.claim c with (nolock)
inner join claim_line cl on c.Claim_ID = cl.Claim_ID and cl.Linenum = 1
left join axiscore.dbo.member_policy mp with (nolock) on c.Member_Policy_ID = mp.Member_Policy_ID
left join axiscore.dbo.policy p with (nolock) on mp.policy_id = p.policy_id
inner join axiscore.dbo.Claim_Status s with (nolock) on c.Claim_Status_ID = s.Claim_Status_ID
left outer join axiscore.dbo.Claim_Reason_Type r with (nolock) on c.Claim_Reason_Type_ID = r.Claim_Reason_Type_ID
where
c.Updated_Date between '10-1-2019' and '10-31-2019'
and p.Payor_ID = 8
and (c.Claim_Status_ID <> 8)
)
select #Total_new_claims_received = count(id)
from cte
where benefit_code_id not in ('739');
with cte2 (ID, Date) as (
select c.id, c.date
from axiscore.dbo.claim c with (nolock)
inner join claim_line cl on c.Claim_ID = cl.Claim_ID and cl.Linenum = 1
left join axiscore.dbo.member_policy mp with (nolock) on c.Member_Policy_ID = mp.Member_Policy_ID
left join axiscore.dbo.policy p with (nolock) on mp.policy_id = p.policy_id
inner join axiscore.dbo.Claim_Status s with (nolock) on c.Claim_Status_ID = s.Claim_Status_ID
left outer join axiscore.dbo.Claim_Reason_Type r with (nolock) on c.Claim_Reason_Type_ID = r.Claim_Reason_Type_ID
where
c.Updated_Date between '10-1-2019' and '10-31-2019'
and p.Payor_ID = 8
and (c.Claim_Status_ID in (7,6))
and (c.Claim_Reason_Type_ID not in (136,137))
)
select #Total_Claims_Processed = count(id)
from cte2
where benefit_code_id not in ('739');

An SQL query with an 'IN' within the where clause is very slow to run

I have created an SQL query which runs but it takes about 17 seconds to complete. I have narrowed down the problem to the IN clause within the Where section of the query. This section is responsible for also finding all records within the same table where the kitref of one record matches the partofkit field of multiple other records.
Could anyone help with suggestions on how I may be able to make this more efficient?
The full SQL is below:
SELECT
tblProductions.ProductionName, tblEquipment.KitRef, tblEquipment.PartOfKit, tblEquipment.Description,
tblCollection.HireID, tblCollection.CollectedBy, Format(tblCollection.DueBack,'dd/MM/yyyy') AS DueBack, Format(tblCollection.CollectionDate,'dd/MM/yyyy') AS CollectionDate, Format(tblCollection.CollectionTime,'HH:mm') AS CollectionTime, tblCollection.DiscountPC,
tblCollectionItemized.HireLine, tblCollectionItemized.Notes, tblCollectionItemized.BookingActive, tblCollectionItemized.DepositReturned, tblTariff.Tariff
FROM tblTariff
INNER JOIN (
tblProductions INNER JOIN (
tblCollection INNER JOIN (
tblEquipment
INNER JOIN tblCollectionItemized ON tblEquipment.KitKey = tblCollectionItemized.KitKey
) ON tblCollection.HireID = tblCollectionItemized.HireID)
ON tblProductions.ProductionIDKey = tblCollection.ProductionName
) ON tblTariff.TariffKey = tblCollection.Tarriff
WHERE (
tblCollectionItemized.BookingActive='TRUE'
AND tblEquipment.PartOfKit IN (
SELECT tblEquipment.KitRef
FROM tblEquipment
INNER JOIN tblCollectionItemized ON tblEquipment.KitKey = tblCollectionItemized.KitKey
WHERE tblCollectionItemized.ReturnsNumber =43
)
)
OR (
tblCollectionItemized.BookingActive='TRUE'
AND tblCollectionItemized.ReturnsNumber =43
)
Not a complete answer here but using some aliases and joins in a logical order make this nightmarish query into something a lot easier to see what is going on.
SELECT
p.ProductionName
, e.KitRef
, e.PartOfKit
, e.Description
, c.HireID
, c.CollectedBy
, Format(c.DueBack,'dd/MM/yyyy') AS DueBack
, Format(c.CollectionDate,'dd/MM/yyyy') AS CollectionDate
, Format(c.CollectionTime,'HH:mm') AS CollectionTime
, c.DiscountPC
, ci.HireLine
, ci.Notes
, ci.BookingActive
, ci.DepositReturned
, t.Tariff
FROM tblTariff t
INNER JOIN tblCollection c ON t.TariffKey = c.Tarriff
INNER JOIN tblProductions p ON p.ProductionIDKey = c.ProductionName
INNER JOIN tblCollectionItemized ci ON c.HireID = ci.HireID
INNER JOIN tblEquipment e ON e.KitKey = ci.KitKey
WHERE ci.BookingActive = 'TRUE'
AND e.PartOfKit IN
(
SELECT e2.KitRef
FROM tblEquipment e2
INNER JOIN tblCollectionItemized ci2 ON e2.KitKey = ci2.KitKey
WHERE ci2.ReturnsNumber = 43
)
OR
(
ci.ReturnsNumber = 43
)
you can try EXISTS instead of IN and add (nolock) hint to tables
SELECT
P.ProductionName,
E.KitRef,
E.PartOfKit,
E.Description,
C.HireID,
C.CollectedBy,
Format(C.DueBack,'dd/MM/yyyy') AS DueBack,
Format(C.CollectionDate,'dd/MM/yyyy') AS CollectionDate,
Format(C.CollectionTime,'HH:mm') AS CollectionTime,
C.DiscountPC,
CI.HireLine,
CI.Notes,
CI.BookingActive,
CI.DepositReturned,
T.Tariff
FROM tblTariff T
INNER JOIN tblCollection C (nolock) ON T.TariffKey = C.Tarriff
INNER JOIN tblProductions P (nolock) ON P.ProductionIDKey = C.ProductionName
INNER JOIN tblCollectionItemized CI (nolock) ON C.HireID = CI.HireID
INNER JOIN tblEquipment E (nolock) ON E.KitKey = CI.KitKey
WHERE (
tblCollectionItemized.BookingActive='TRUE'
AND EXISTS (
SELECT *
FROM tblEquipment E2 (nolock)
INNER JOIN tblCollectionItemized CI2 (nolock) ON E2.KitKey = CI2.KitKey
WHERE CI2.ReturnsNumber =43 AND E.PartOfKit = E2.KitRef )
)
OR (
CI.BookingActive='TRUE'
AND CI.ReturnsNumber =43
)

connot perform an aggregate function ... with GROUP BY

Hello i'm trying to write a query which consists to calculate the sum of 2 values, the second sum is result of multiplication between the first value and another. could someone help to solve this please ?? ( excuse me for my english, im frensh developer ) :
SELECT ISNULL(CONVERT(VARCHAR,CONVERT(date,MARE_DAT_CRE,103)),'Total') AS Dat
, SUM (MARE_CAUTIONNEMENT) AS HT
, SUM ( MARE_CAUTIONNEMENT * ( SELECT DISTINCT LCF_TAUXTVA
FROM F_LIGNECOMFOU
INNER JOIN F_AFFAIRES ON LCF_CODE_AFF = AF_CODE_AFFAIRE
INNER JOIN F_LOT ON LT_AFFAIRE = AF_CODE_AFFAIRE
INNER JOIN F_COMMANDEFOU ON CF_NUMERO = LCF_CF_NUMERO
INNER JOIN F_P_FOURNISSEUR ON CF_IDENT_FO = FOU_IDENT
WHERE AF_CODE_AFFAIRE = '15065-00' AND LT_IDENT = 500002200 AND FOU_IDENT = 500000838 ) ) FROM F_AVENANT_RETENUE INNER JOIN F_MARCHE_AVENANT ON MAAV_IDENT = MARE_MAAV_IDENT INNER JOIN F_MARCHE_TRAVAUX ON MATR_IDENT = MAAV_MATR_IDENT INNER JOIN F_AFFAIRES ON AF_CODE_AFFAIRE = MATR_AF_IDENT INNER JOIN F_LOT ON LT_AFFAIRE = AF_CODE_AFFAIRE INNER JOIN F_AVENANT_COTATION ON AVCO_IDENT = MARE_AVCO_IDENT WHERE AF_CODE_AFFAIRE = '15065-00' AND LT_IDENT = 500002200 AND MATR_FOU_IDENT = 500000838 AND MARE_CAUTIONNEMENT IS NOT NULL
GROUP BY MARE_DAT_CRE WITH ROLLUP
You could try sticking that sub select in your joins. Now you haven't used table alias so I'm not sure which tables contain the fields AF_CODE_AFFAIRE, LT_IDENT and MATR_FOU_IDENT so you'll have to add table aliases;
SELECT ISNULL(CONVERT(VARCHAR, CONVERT(DATE, MARE_DAT_CRE, 103)), 'Total') AS Dat
,SUM(MARE_CAUTIONNEMENT) AS HT
,SUM(MARE_CAUTIONNEMENT) * SUM(new.LCF_TAUXTVA)
FROM F_AVENANT_RETENUE
INNER JOIN F_MARCHE_AVENANT ON MAAV_IDENT = MARE_MAAV_IDENT
INNER JOIN F_MARCHE_TRAVAUX ON MATR_IDENT = MAAV_MATR_IDENT
INNER JOIN F_AFFAIRES ON AF_CODE_AFFAIRE = MATR_AF_IDENT
INNER JOIN F_LOT ON LT_AFFAIRE = AF_CODE_AFFAIRE
INNER JOIN F_AVENANT_COTATION ON AVCO_IDENT = MARE_AVCO_IDENT
LEFT JOIN (
SELECT DISTINCT LCF_TAUXTVA
FROM F_LIGNECOMFOU
INNER JOIN F_AFFAIRES ON LCF_CODE_AFF = AF_CODE_AFFAIRE
INNER JOIN F_LOT ON LT_AFFAIRE = AF_CODE_AFFAIRE
INNER JOIN F_COMMANDEFOU ON CF_NUMERO = LCF_CF_NUMERO
INNER JOIN F_P_FOURNISSEUR ON CF_IDENT_FO = FOU_IDENT
) new ON AF_CODE_AFFAIRE = new.AF_CODE_AFFAIRE
AND LT_IDENT = new.LT_IDENT
AND MATR_FOU_IDENT = new.MATR_FOU_IDENT
WHERE AF_CODE_AFFAIRE = '15065-00'
AND LT_IDENT = 500002200
AND MATR_FOU_IDENT = 500000838
AND MARE_CAUTIONNEMENT IS NOT NULL
GROUP BY ISNULL(CONVERT(VARCHAR, CONVERT(DATE, MARE_DAT_CRE, 103)), 'Total')
WITH ROLLUP

Syntax error in Join Operation- MS Access inline join statement

I am trying to run below query but I am getting error on MS Access, "Syntax error in Join Operation"
Below is my query -
select
v.City,
v.CURRENCY,
(
select
Sum(VSDEH.NORM_PRICE_MEDIUM*BCIEH.WEIGHT_OR_MULTIPLIER) AS BaseMedium
FROM (
// This line has error ->> ([VSURVEYDATA] AS VSDEH INNER JOIN [BASKET_CONTENT_ITEMS] AS BCIEH ON VSDEH.ITEM = BCIEH.ITEM_ID)
INNER JOIN [EXCHANGE_RATES] AS EXREH on VSDEH.SURVEY_DATE = EXREH.RATE_DATE AND VSDEH.CURRENCY = EXREH.BASE_CURRENCY_ID
)
WHERE (
VSDEH.SURVEY_DATE = v.SURVEY_DATE
AND BCIEH.LINE_OF_BUSINESS_ID='ICOL'
AND BCIEH.BASKET_ID= b.BASKET_ID
AND BCIEH.ITEM_ID not in ( '215','216','326')
AND EXREH.HOST_CURRENCY_ID= ex.HOST_CURRENCY_ID
AND EXREH.RATE_SET_ID=' '
AND VSDEH.CITY in (v.City)
)
GROUP BY VSDEH.CITY, VSDEH.CURRENCY
) as BaseMediumEH
FROM ((
([VSURVEYDATA] AS VSDEH INNER JOIN [BASKET_CONTENT_ITEMS] AS BCIEH ON VSDEH.ITEM = BCIEH.ITEM_ID)
INNER JOIN [EXCHANGE_RATES] AS EXREH on VSDEH.SURVEY_DATE = EXREH.RATE_DATE AND VSDEH.CURRENCY = EXREH.BASE_CURRENCY_ID
)
INNER JOIN qSTAHostCity ON VSURVEYDATA.CITY = qSTAHostCity.HostCity)
WHERE (
v.SURVEY_DATE = [Survey Date]
AND b.LINE_OF_BUSINESS_ID='ICOL'
AND b.BASKET_ID= [Basket ID]
AND ex.HOST_CURRENCY_ID='USD'
AND ex.RATE_SET_ID=' ')
GROUP BY v.CITY, v.CURRENCY ORDER BY v.CITY
Can anyone suggest what am I doing wrong here ?
Thanks
You miss two table alias :
Replace *****TableAlias***** by the table alias name you need to do your join.
select
v.City,
v.CURRENCY,
(
select
Sum(VSDEH.NORM_PRICE_MEDIUM*BCIEH.WEIGHT_OR_MULTIPLIER) AS BaseMedium
FROM (
// This line has error ->> ([VSURVEYDATA] AS VSDEH INNER JOIN [BASKET_CONTENT_ITEMS] AS BCIEH ON VSDEH.ITEM = BCIEH.ITEM_ID) *****TableAlias*****
INNER JOIN [EXCHANGE_RATES] AS EXREH on VSDEH.SURVEY_DATE = EXREH.RATE_DATE AND VSDEH.CURRENCY = EXREH.BASE_CURRENCY_ID
)
WHERE (
VSDEH.SURVEY_DATE = v.SURVEY_DATE
AND BCIEH.LINE_OF_BUSINESS_ID='ICOL'
AND BCIEH.BASKET_ID= b.BASKET_ID
AND BCIEH.ITEM_ID not in ( '215','216','326')
AND EXREH.HOST_CURRENCY_ID= ex.HOST_CURRENCY_ID
AND EXREH.RATE_SET_ID=' '
AND VSDEH.CITY in (v.City)
)
GROUP BY VSDEH.CITY, VSDEH.CURRENCY
) as BaseMediumEH
FROM ((
([VSURVEYDATA] AS VSDEH INNER JOIN [BASKET_CONTENT_ITEMS] AS BCIEH ON VSDEH.ITEM = BCIEH.ITEM_ID) *****TableAlias*****
INNER JOIN [EXCHANGE_RATES] AS EXREH on VSDEH.SURVEY_DATE = EXREH.RATE_DATE AND VSDEH.CURRENCY = EXREH.BASE_CURRENCY_ID
)
INNER JOIN qSTAHostCity ON VSURVEYDATA.CITY = qSTAHostCity.HostCity)
WHERE (
v.SURVEY_DATE = [Survey Date]
AND b.LINE_OF_BUSINESS_ID='ICOL'
AND b.BASKET_ID= [Basket ID]
AND ex.HOST_CURRENCY_ID='USD'
AND ex.RATE_SET_ID=' ')
GROUP BY v.CITY, v.CURRENCY ORDER BY v.CITY