I have these 2 queries that almost give me the data I need:
SELECT Products.ItemID, Products.ItemID + '-' + ModifierListItems.ItemID AS SizeItemID
FROM ModifierLists INNER JOIN
ProductModifierLists ON ModifierLists.ModifierListID = ProductModifierLists.ModifierListID INNER JOIN
ModifierListItems ON ModifierLists.ModifierListID = ModifierListItems.ModifierListID INNER JOIN
Products ON ProductModifierLists.ItemID = Products.ItemID AND ProductModifierLists.ManufacturerID = Products.ManufacturerID
WHERE (Products.ManufacturerID = 262) AND ModifierListName='Size'
ORDER BY Products.ItemID
SELECT Products.ItemID, ModifierListItems.ItemID AS ColorItemID
FROM ModifierLists INNER JOIN
ProductModifierLists ON ModifierLists.ModifierListID = ProductModifierLists.ModifierListID INNER JOIN
ModifierListItems ON ModifierLists.ModifierListID = ModifierListItems.ModifierListID INNER JOIN
Products ON ProductModifierLists.ItemID = Products.ItemID AND ProductModifierLists.ManufacturerID = Products.ManufacturerID
WHERE (Products.ManufacturerID = 262) AND ModifierListName='Color'
ORDER BY Products.ItemID
The final output I am looking for is the SizeItemID concatenated with the ColorItemID joined on the ItemID.
Sample results of the 2 queries:
ItemID SizeItemID
------- ----------
A A-S
A A-M
B B-M
B B-L
ItemID ColorItemID
------- -----------
A BLK
A WHT
B BLK
B WHT
B GRN
The results I am looking for would be the following:
FinalItemID
-----------
A-S-BLK
A-S-WHT
A-M-BLK
A-M-WHT
B-M-BLK
B-M-WHT
B-M-GRN
B-L-BLK
B-L-WHT
B-L-GRN
You can take your two queries and join them together on ItemId to construct the final value.
In the following query, I also use aliases on your table names. Many people find meaningful aliases easier to read than long table names:
with tsize as (
SELECT p.ItemID,
p.ItemID + '-' + mli.ItemID AS SizeItemID
FROM ModifierLists ml INNER JOIN
ProductModifierLists pml
ON ml.ModifierListID = pml.ModifierListID INNER JOIN
ModifierListItems mli
ON ml.ModifierListID = mli.ModifierListID INNER JOIN
Products p
ON pml.ItemID = Products.ItemID AND
pml.ManufacturerID = p.ManufacturerID
WHERE (p.ManufacturerID = 262) AND ModifierListName='Size'
),
tcolor as (
SELECT p.ItemID, mli.ItemID AS ColorItemID
FROM ModifierLists moli INNER JOIN
ProductModifierLists pml
ON ml.ModifierListID = pml.ModifierListID INNER JOIN
ModifierListItems mli
ON ml.ModifierListID = mli.ModifierListID INNER JOIN
Products p
ON pml.ItemID = Products.ItemID AND
pml.ManufacturerID = p.ManufacturerID
WHERE (Products.ManufacturerID = 262) AND ModifierListName='Color'
)
select SizeItemID+'-'+ColorItemID
from tsize join tcolor
on tsize.itemid = tcolor.ItemID
Well, the cleanest looking way would be to put each query into it's own view. It also might help you understand what you're doing a little better. So if we took the queries and created views:
CREATE VIEW v_ProductSize
AS
SELECT Products.ItemID, Products.ItemID + '-' + ModifierListItems.ItemID AS SizeItemID
FROM ModifierLists INNER JOIN
ProductModifierLists ON ModifierLists.ModifierListID = ProductModifierLists.ModifierListID INNER JOIN
ModifierListItems ON ModifierLists.ModifierListID = ModifierListItems.ModifierListID INNER JOIN
Products ON ProductModifierLists.ItemID = Products.ItemID AND ProductModifierLists.ManufacturerID = Products.ManufacturerID
WHERE (Products.ManufacturerID = 262) AND ModifierListName='Size'
ORDER BY Products.ItemID
CREATE VIEW v_ProductColor
AS
SELECT Products.ItemID, ModifierListItems.ItemID AS ColorItemID
FROM ModifierLists INNER JOIN
ProductModifierLists ON ModifierLists.ModifierListID = ProductModifierLists.ModifierListID INNER JOIN
ModifierListItems ON ModifierLists.ModifierListID = ModifierListItems.ModifierListID INNER JOIN
Products ON ProductModifierLists.ItemID = Products.ItemID AND ProductModifierLists.ManufacturerID = Products.ManufacturerID
WHERE (Products.ManufacturerID = 262) AND ModifierListName='Color'
ORDER BY Products.ItemID
Then you have two simple views you can use normally, right? So your query would be:
SELECT ps.SizeItemID + '-' + pc.ColorItemID
FROM v_ProductSize ps
JOIN v_ProductColor pc ON ps.ItemID=pc.ItemID
See how that works? You're just doing a normal join like you would any other table. Now, say you don't want to create views, or for some reason don't have permission. You can just skip the view part itself, and use subqueries. You're just replacing the reference to the view, with the query itself in parentheses.
So it would look like this:
SELECT ps.SizeItemID + '-' + pc.ColorItemID
FROM (
SELECT Products.ItemID, Products.ItemID + '-' + ModifierListItems.ItemID AS SizeItemID
FROM ModifierLists INNER JOIN
ProductModifierLists ON ModifierLists.ModifierListID = ProductModifierLists.ModifierListID INNER JOIN
ModifierListItems ON ModifierLists.ModifierListID = ModifierListItems.ModifierListID INNER JOIN
Products ON ProductModifierLists.ItemID = Products.ItemID AND ProductModifierLists.ManufacturerID = Products.ManufacturerID
WHERE (Products.ManufacturerID = 262) AND ModifierListName='Size'
ORDER BY Products.ItemID
) ps
JOIN
( SELECT Products.ItemID, ModifierListItems.ItemID AS ColorItemID
FROM ModifierLists INNER JOIN
ProductModifierLists ON ModifierLists.ModifierListID = ProductModifierLists.ModifierListID INNER JOIN
ModifierListItems ON ModifierLists.ModifierListID = ModifierListItems.ModifierListID INNER JOIN
Products ON ProductModifierLists.ItemID = Products.ItemID AND ProductModifierLists.ManufacturerID = Products.ManufacturerID
WHERE (Products.ManufacturerID = 262) AND ModifierListName='Color'
ORDER BY Products.ItemID
) pc ON ps.itemID=pc.ItemID
Now... all that said, and with my coffee finally kicking in, you can greatly simplify the query into one with a one line modification:
SELECT Products.ItemID, Products.ItemID + '-' + colors.ItemID + '-' + sizes.ItemID AS SizeColorItemID
FROM ModifierLists
INNER JOIN ProductModifierLists ON ModifierLists.ModifierListID = ProductModifierLists.ModifierListID
INNER JOIN ModifierListItems sizes ON ModifierLists.ModifierListID = ModifierListItems.ModifierListID
--Put modifier list name in join clause
AND ModifierListName='Size'
INNER JOIN ModifierListItems colors ON ModifierLists.ModifierListID = ModifierListItems.ModifierListID
--same here, but for color
AND ModifierListName = 'Color'
INNER JOIN Products ON ProductModifierLists.ItemID = Products.ItemID
AND ProductModifierLists.ManufacturerID = Products.ManufacturerID
WHERE (Products.ManufacturerID = 262) --Remove modifierlistitem here so you can use it in the join clauses
ORDER BY Products.ItemID
So since we're really pulling the same information in both original queries, with just a single different condition... we can move the modifierlistitem.name into the join clause, then join to that same table again with a different condition. Then we alias the table based on which condition we used (size, color.) That way you can just refer to the alias and pull the correct item id, and concatenate them all at once.
Try this:
You just need make both the queries as derived tables and join on ItemID
Select a.SizeItemID+'-'+b.ColorItemID as FinalItemID
FROM
(SELECT Products.ItemID, Products.ItemID + '-' + ModifierListItems.ItemID AS SizeItemID
FROM ModifierLists INNER JOIN
ProductModifierLists ON ModifierLists.ModifierListID = ProductModifierLists.ModifierListID INNER JOIN
ModifierListItems ON ModifierLists.ModifierListID = ModifierListItems.ModifierListID INNER JOIN
Products ON ProductModifierLists.ItemID = Products.ItemID AND ProductModifierLists.ManufacturerID = Products.ManufacturerID
WHERE (Products.ManufacturerID = 262) AND ModifierListName='Size'
)a
JOIN
(SELECT Products.ItemID, ModifierListItems.ItemID AS ColorItemID
FROM ModifierLists INNER JOIN
ProductModifierLists ON ModifierLists.ModifierListID = ProductModifierLists.ModifierListID INNER JOIN
ModifierListItems ON ModifierLists.ModifierListID = ModifierListItems.ModifierListID INNER JOIN
Products ON ProductModifierLists.ItemID = Products.ItemID AND ProductModifierLists.ManufacturerID = Products.ManufacturerID
WHERE (Products.ManufacturerID = 262) AND ModifierListName='Color'
)b
on a.ItemID=b.ItemID
ORDER BY a.FinalItemID
Related
I need help with a select in postgres, I need to group X types into a single line, for example: type: multiple, trully, I need help on the type column
SELECT tbl_questions.id AS id,
tbl_questions.question AS question,
tbl_questions.year AS year,
tbl_question_responses.response_id AS response_id,
tbl_responses.response AS response_content,
tbl_responses.response_type AS response,
tbl_subjects.name AS subject,
tbl_categories.name AS category,
tbl_types.name AS type,
tbl_institutions.name AS institution
FROM tbl_questions
INNER JOIN tbl_question_responses ON tbl_questions.id = tbl_question_responses.question_id
INNER JOIN tbl_responses ON tbl_question_responses.response_id = tbl_responses.id
INNER JOIN tbl_question_subjects ON tbl_questions.id = tbl_question_subjects.question_id
INNER JOIN tbl_subjects ON tbl_subjects.id = tbl_question_subjects.subject_id
INNER JOIN tbl_question_categories ON tbl_questions.id = tbl_question_categories.question_id
INNER JOIN tbl_categories ON tbl_categories.id = tbl_question_categories.category_id
INNER JOIN tbl_question_types ON tbl_questions.id = tbl_question_types.question_id
INNER JOIN tbl_types ON tbl_types.id = tbl_question_types.type_id
INNER JOIN tbl_question_institutions ON tbl_question_institutions.question_id = tbl_questions.id
INNER JOIN tbl_institutions ON tbl_institutions.id = tbl_question_institutions.institution_id
WHERE tbl_questions.id = 'c7aa15cb-27e5-4f28-9141-483f7cce8e56'
This is a select result
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
Hi i have one sql query in sql server that looks like
SELECT
DTST.[Id],
FPT.[StartTime],
--FPT.[BusinessTypeId],
FPT.[PaymentMethodId],
FPT.[3DSecureId],
FPT.[ProductId],
DPT.[Id],
FPT.[TransactionStatusId],
FPT.[Amount],
DC.[Code],
FPT.[PlayerId],
DPL.[SourceOrigId],
DPL.[Username],
DPL.[FirstName],
DPL.[LastName],
DPL.[BrandId],
DPL.[VIPLevelId],
DPL.[MarketingChannelId],
DPL.[MarketingSourceId],
FPT.[PaymentReasonTextId],
FPT_Ref.[PaymentReasonTextId],
AD.Username,
FPT.[OriginalTransactionId],
FPT.[TransactionId],
FPT_Ref.[OriginalTransactionId],
FPT.[ProviderTransactionOrigId]
FROM WarehouseMgmt.FactPaymentTrans AS FPT
JOIN
(
SELECT TransactionId,MAX(TransactionStepId) TransactionStepId
FROM [WarehouseMgmt].[FactPaymentTrans]
WHERE FactType = ''SOURCE''
GROUP BY TransactionId
) AS FPT_Last ON FPT.TransactionId = FPT_Last.TransactionId AND FPT.TransactionStepId = FPT_Last.TransactionStepId
JOIN WarehouseMgmt.DimTransactionStepType AS DTST ON FPT.[TransactionStepTypeId] = DTST.[Id]
JOIN WarehouseMgmt.DimCurrency AS DC ON FPT.CurrencyId = DC.Id
JOIN WarehouseMgmt.DimPlayer AS DPL ON FPT.PlayerId = DPL.Id
JOIN WarehouseMgmt.DimProduct AS DP ON DP.Id = FPT.ProductId
JOIN WarehouseMgmt.DimProductType AS DPT ON DPT.Id = DP.ProductTypeId
JOIN [WarehouseMgmt].[DimLoyaltyProgramLevel] DLPL ON DLPL.[Id]=DPL.VipLevelId
JOIN WarehouseMgmt.DimAdmin AS AD ON AD.Id=FPT.CreatedByAdminId
JOIN WarehouseMgmt.DimPaymentTransactionBusinessType AS DPTBT ON DPTBT.Id = FPT.BusinessTypeId
JOIN WarehouseMgmt.DimTransactionStatus TS ON TS.Id= FPT.TransactionStatusId
JOIN WarehouseMgmt.DimPaymentMethod DPM ON DPM.Id = FPT.[PaymentMethodId]
JOIN WarehouseMgmt.DimTimeZone DTZ on FPT.[TimeId] = DTZ.TimeUTCId
LEFT JOIN [WarehouseMgmt].[FactPaymentTrans] FPT_Ref ON FPT_Ref.OriginalTransactionId = FPT.TransactionId AND FPT_Ref.FactType = ''SOURCE''
WHERE (FPT.FactType = ''SOURCE'')
AND DTZ.TimeId BETWEEN #DimStartDate AND #DimEndDate ' + #sqlFilters
With this query i have duplicated transactions, because of LEFT JOIN. How can i improve my LEFT JOIN to take only MAX TransactionId in from LEFT JOIN ?
I have the following query
SELECT *
INTO ##TempStaffT
FROM Staff HF
WHERE HF.[businessline_id]='T'
AND HF.[offices_id] IN (SELECT * FROM ##TempParamOffice)
AND HF.[specialism_id]IN (SELECT * FROM ##TempParamSpecialism)
AND HF.[onetouch]IN (SELECT * FROM ##TempParamConsultant)
SET #sql4 = N'
INSERT INTO ##TempFees(' + #columns1 + ',CALF_AN ,BusinessName)
SELECT distinct ' + #columns2 + ',p.CALF_AN ,CB.[TempBusinessName] as BusinessName
FROM
dbo.WTEFAC EF
inner JOIN dbo.WTFAC F ON EF.EFAC_NUM = F.EFAC_NUM
inner JOIN dbo.WTFACINFO BS ON F.FAC_NUM = BS.FAC_NUM
inner JOIN dbo.WTLFAC LF ON F.FAC_NUM = LF.FAC_NUM
inner JOIN dbo.WTRUBVARIANTEFAC WRU ON LF.RINT_ID = WRU.RINT_ID
inner JOIN dbo.WTACUMFAC WTA ON WRU.RUV_ID = WTA.RUV_ID
inner JOIN ##CUM_CODEHT WTA1 ON WTA.CUM_ID = WTA1.CUM_ID
inner JOIN dbo.WTVTAT TAT ON BS.TIE_ID = TAT.TIE_ID AND BS.RFAN_ID = TAT.RFAN_ID AND BS.PER_ID = TAT.PER_ID AND BS.CNT_ID = TAT.CNT_ID
inner JOIN dbo.PYCONTRAT CC ON TAT.PER_ID = CC.PER_ID AND TAT.CNT_ID = CC.CNT_ID
inner JOIN dbo.WTMISS M ON CC.PER_ID = M.PER_ID AND CC.CNT_ID = M.CNT_ID
inner JOIN dbo.WTCNTI COT1 ON M.PER_ID = COT1.PER_ID AND M.CNT_ID = COT1.CNT_ID
inner JOIN dbo.WTQUAEU Q ON COT1.TIE_ID = Q.TIE_ID AND COT1.QEU_CDE = Q.QEU_CDE
inner JOIN dbo.WTSCCT C ON CC.RGPCNT_ID = C.RGPCNT_ID AND CC.PER_ID = C.PER_ID AND CC.CNT_ID = C.CNT_ID --AND''SECT3'' = C.STTQ_COD
INNER JOIN ##TempStaffT HF ON C.VAPO_CODE = HF.onetouch COLLATE Latin1_General_CI_AS
inner JOIN
##TempA AS p ON p.CNT_ID = COT1.CNT_ID inner JOIN
##TempB AS p1 ON p1.CNT_ID = COT1.CNT_ID
CROSS JOIN [dbo].[CustBusinessTable] CB
WHERE CB.[TempBusinessName]=''Pure Temp Fees''
GROUP BY p.CALF_AN,CB.[TempBusinessName]
'
;
PRINT #sql4;
My problem is that the query above took 20 min to be executed because ##TempStaffT contains too many rows , how can I optimize it ? I use many temp tables but it seems not to be worked , Any idea ? Many thanks in advance .
Create an index on ##TempStaffT
CREATE INDEX IDX_TempStaffT_onetouch ON ##TempStaffT(onetouch)
I have four tables and I need to find the average of each score for a particular id. I do not need the ENTIRE Column average, but the average of each record with the same id in each table.
I have tried this:
SELECT DISTINCT M.system_id, S.name, SUM(A.Score + WAL.score + F.score + WIN.score) / 4
AS avgScore
FROM dbo.T3_MovementSystemJoin AS M
INNER JOIN dbo.T3_systems AS S ON M.system_id = S.id
INNER JOIN T3_ApplicationSystemJoin AS A ON A.Application_id = #application_id
INNER JOIN T3_WallTypeSystemJoin AS WAL ON WAL.wall_id = #wall_id
INNER JOIN T3_FenestrationSystemJoin AS F ON F.fenestration_id = #fen_id
INNER JOIN T3_WindowOrientation_System AS WIN ON WIN.window_id = #window_id
INNER JOIN T3_ConstructionSystemJoin AS C ON C.contruction_id = #construction_id
INNER JOIN T3_JointDepthSystemJoin AS J ON J.JointDepth_id = #JointDepth_id
INNER JOIN T3_JointGapSystemJoin AS JG ON JG.JointGap_id = #JointGap_id
WHERE (M.movement_id = #movement_id)
GROUP BY M.System_id, S.name
:
Thanks for your help!
No Sum needed (and no grouping too)
SELECT DISTINCT M.system_id, S.name, (IsNull(A.Score, 0) + IsNull(WAL.score, 0) + IsNull(F.score, 0) + IsNull(WIN.score, 0)) /4
as avgscore
FROM dbo.T3_MovementSystemJoin AS M
INNER JOIN dbo.T3_systems AS S ON M.system_id = S.id
INNER JOIN T3_ApplicationSystemJoin AS A ON A.Application_id = #application_id
INNER JOIN T3_WallTypeSystemJoin AS WAL ON WAL.wall_id = #wall_id
INNER JOIN T3_FenestrationSystemJoin AS F ON F.fenestration_id = #fen_id
INNER JOIN T3_WindowOrientation_System AS WIN ON WIN.window_id = #window_id
INNER JOIN T3_ConstructionSystemJoin AS C ON C.contruction_id = #construction_id
INNER JOIN T3_JointDepthSystemJoin AS J ON J.JointDepth_id = #JointDepth_id
INNER JOIN T3_JointGapSystemJoin AS JG ON JG.JointGap_id = #JointGap_id
WHERE (M.movement_id = #movement_id)
SELECT DISTINCT M.system_id
,S.name
,(ISNULL(A.Score,0) + ISNULL(WAL.score,0) + ISNULL(F.score,0) + ISNULL(WIN.score,0)) /4 as 'AvgScore'
FROM dbo.T3_MovementSystemJoin AS M
INNER JOIN dbo.T3_systems AS S ON M.system_id = S.id
INNER JOIN T3_ApplicationSystemJoin AS A ON A.Application_id = #application_id
INNER JOIN T3_WallTypeSystemJoin AS WAL ON WAL.wall_id = #wall_id
INNER JOIN T3_FenestrationSystemJoin AS F ON F.fenestration_id = #fen_id
INNER JOIN T3_WindowOrientation_System AS WIN ON WIN.window_id = #window_id
INNER JOIN T3_ConstructionSystemJoin AS C ON C.contruction_id = #construction_id
INNER JOIN T3_JointDepthSystemJoin AS J ON J.JointDepth_id = #JointDepth_id
INNER JOIN T3_JointGapSystemJoin AS JG ON JG.JointGap_id = #JointGap_id
WHERE (M.movement_id = #movement_id)
If you don't want NULL values to become zeros and included in the average:
SELECT DISTINCT M.system_id, S.name, X.avgScore
FROM dbo.T3_MovementSystemJoin AS M
INNER JOIN dbo.T3_systems AS S ON M.system_id = S.id
INNER JOIN T3_ApplicationSystemJoin AS A ON A.Application_id = #application_id
INNER JOIN T3_WallTypeSystemJoin AS WAL ON WAL.wall_id = #wall_id
INNER JOIN T3_FenestrationSystemJoin AS F ON F.fenestration_id = #fen_id
INNER JOIN T3_WindowOrientation_System AS WIN ON WIN.window_id = #window_id
INNER JOIN T3_ConstructionSystemJoin AS C ON C.contruction_id = #construction_id
INNER JOIN T3_JointDepthSystemJoin AS J ON J.JointDepth_id = #JointDepth_id
INNER JOIN T3_JointGapSystemJoin AS JG ON JG.JointGap_id = #JointGap_id
CROSS APPLY ( SELECT AVG(s) FROM (VALUES (A.Score),(WAL.score),(F.score),(WIN.score) ) scores(s) ) X(avgScore)
WHERE (M.movement_id = #movement_id)
GROUP BY M.System_id, S.name