试试这个:
WITH cte as(
SELECT * FROM K1
UNION ALL
SELECT * FROM K2
UNION ALL
SELECT * FROM K3
UNION ALL
SELECT * FROM K4
), FirstColl as (SELECT * FROM (Select DP, RN, ET, ED, DT, COUNT(*)OVER(PARTITION BY DP, RN) AS your_count
from cte) a WHERE your_count = 1 and ET = 'Complete' and DT = 'STR'
), SecondColl as (SELECT * FROM (Select DP, RN, ET, ED, DT, COUNT(*)OVER(PARTITION BY DP, RN) AS your_count
from cte) a WHERE your_count = 1 and ET = 'Complete' and DT = 'NCD'
)
select
a.STRMnth, a.cnt1 as STRRFT, b.cnt2 as STRAFT
from
(select month(ED) as STRMnth, count(*) as cnt1 from FirstColl group by month(ED)) a
left join
(select month(ED) as STRMnth, count(*) as cnt2 from SecondColl group by month(ED)) b
on a.STRMnth = b.STRMnth
order by a.STRMnth asc
UPDATE1:
WITH cte as(
SELECT * FROM K1
UNION ALL
SELECT * FROM K2
UNION ALL
SELECT * FROM K3
UNION ALL
SELECT * FROM K4
), FirstColl as (SELECT * FROM (Select DP, RN, ET, ED, DT, COUNT(*)OVER(PARTITION BY DP, RN) AS your_count
from cte) a WHERE your_count = 1 and ET = 'Complete' and DT = 'STR'
), SecondColl as (SELECT * FROM (Select DP, RN, ET, ED, DT, COUNT(*)OVER(PARTITION BY DP, RN) AS your_count
from cte) a WHERE your_count = 1 and ET = 'Complete' and DT = 'NCD'
), ThirdColl as (SELECT Distinct ED, DP, RN FROM cte WHERE DT = 'STR')
select
a.STRMnth, a.cnt1 as STRRFT, b.cnt2 as STRAFT
from
(select month(ED) as STRMnth, count(*) as cnt1 from FirstColl group by month(ED)) a
left join
(select month(ED) as STRMnth, count(*) as cnt2 from SecondColl group by month(ED)) b
on a.STRMnth = b.STRMnth
left join
(select month(ED) as STRMnth, count(*) as cnt3 from ThirdColl group by month(ED)) c
on a.STRMnth = c.STRMnth
order by a.STRMnth asc
UPDATE2:
WITH cte as(
SELECT * FROM K1
UNION ALL
SELECT * FROM K2
UNION ALL
SELECT * FROM K3
UNION ALL
SELECT * FROM K4
), FirstColl as (SELECT * FROM (Select DP, RN, ET, ED, DT, COUNT(*)OVER(PARTITION BY DP, RN) AS your_count
from cte) a WHERE your_count = 1 and ET = 'Complete' and DT = 'STR'
), SecondColl as (SELECT * FROM (Select DP, RN, ET, ED, DT, COUNT(*)OVER(PARTITION BY DP, RN) AS your_count
from cte) a WHERE your_count = 1 and ET = 'Complete' and DT = 'NCD'
), ThirdColl as (SELECT distinct ED, DP, RN FROM K1 WHERE Defect_Type = 'STR')
select
a.STRMnth, a.cnt1 as STRRFT, b.cnt2 as STRAFT
from
(select month(ED) as STRMnth, count(*) as cnt1 from FirstColl group by month(ED)) a
left join
(select month(ED) as STRMnth, count(*) as cnt2 from SecondColl group by month(ED)) b
on a.STRMnth = b.STRMnth
left join
(select month(ED) as STRMnth, count(*) as cnt3 from ThirdColl group by month(ED)) c
on a.STRMnth = c.STRMnth
order by a.STRMnth asc
添加一些样品台DAT a和预期结果 - 作为格式化文本。 (即没有图像) – jarlh