我有两张桌子。我需要使用一些连接或子查询来加入它们。 “DWVertical Group”列(第2表)的值应来自第1个表。我该如何实现呢?
第一张表
Declare @Date Date = ( Select Max(RecordDate) from dw_UtilizationPredictionReport)
SELECT
t1.RecordDate,
t1.DWVerticalGroup,
t1.OnOff,
t1.LocationGrouping,
t1.WFMGrade,
t1.BHRS,
t1.AHRS,
t1.OffTFTE,
t1.OffBFTE,
COALESCE(t2.CTFTE, 0) CTFTE,
COALESCE(t2.OverallFTE, 0) OverallFTE,
COALESCE(t3.ATFTE,0) ATFTE,
COALESCE(t3.SATFTE,0) SATFTE,
COALESCE(t4.WCTFTE,0) WCTFTE,
COALESCE(PAQ.COST,0) PAQCOST
FROM
(
SELECT RecordDate, DWVerticalGroup , OnOff, LocationGrouping, WFMGrade,
SUM(BilledHrs) BHRS, SUM(AvailableHrs) AHRS, SUM(TotalFTE) OffTFTE,
SUM(BilledFTE) OffBFTE
FROM dw_UtilizationPredictionReport
WHERE RecordDate=@Date AND OnOff = 'Offshore'
GROUP BY
DWVerticalGroup, OnOff, LocationGrouping, WFMGrade, RecordDate
) t1
第二个表('DWVertical Group'列的值应来自第一个表)
y_labels
1
4
4
3
答案 0 :(得分:0)
你可以使用左连接来实现这个 -
Declare @Date Date = ( Select Max(RecordDate) from dw_UtilizationPredictionReport)
SELECT
t1.RecordDate,
case when t2.VerticalNameGroup is not null then t1.DWVerticalGroup else 'Others' end as DWVerticalGroup ,
t1.OnOff,
t1.LocationGrouping,
t1.WFMGrade,
t1.BHRS,
t1.AHRS,
t1.OffTFTE,
t1.OffBFTE,
COALESCE(t2.CTFTE, 0) CTFTE,
COALESCE(t2.OverallFTE, 0) OverallFTE,
COALESCE(t3.ATFTE,0) ATFTE,
COALESCE(t3.SATFTE,0) SATFTE,
COALESCE(t4.WCTFTE,0) WCTFTE,
COALESCE(PAQ.COST,0) PAQCOST
FROM
(
SELECT RecordDate, DWVerticalGroup , OnOff, LocationGrouping, WFMGrade,
SUM(BilledHrs) BHRS, SUM(AvailableHrs) AHRS, SUM(TotalFTE) OffTFTE,
SUM(BilledFTE) OffBFTE
FROM dw_UtilizationPredictionReport
WHERE RecordDate=@Date AND OnOff = 'Offshore'
GROUP BY
DWVerticalGroup, OnOff, LocationGrouping, WFMGrade, RecordDate
) t1
left join CDB_Verticals as t2
on t2.VerticalNameGroup = t1.DWVerticalGroup and ServiceLine='N'