我有两个单独的选择语句。它们都选择了PrimaryID,但它们也选择了未共享的列,例如PrimaryID。我正在使用内部联接来获得我的结果,如下所示:
PrimaryID | col2 | col3 | PrimaryID | col4 | col5
1 2 3 1 2 3
1 3 4 1 3 4
1 5 6 1 5 6
2 3 4 2 3 4
2 5 6 2 5 6
2 7 8 2 7 8
想要的是:
PrimaryID | col2 | col3 | PrimaryID | col4 | col5
1 2 3 1 2 3
1 3 4
1 5 6
2 3 4 2 3 4
2 5 6
2 7 8
无论如何我能做到这一点吗?感谢。
QUERY:
Select * from
(SELECT primaryid, col2, col3
from g.table
left join (random stuff)
WHERE DATEPART(m, CreateDateTime) = DATEPART(m, DATEADD(m, -1, getdate()))
AND DATEPART(yyyy, CreateDateTime) = DATEPART(yyyy, DATEADD(m, -1, getdate()))) t1
inner join
(select primaryid, col4, col5
from g.table
where primaryid in (select primaryid from g.table) and col5 = 0) t2
on t1.primaryid = t2.primaryid
order by t1.col2
答案 0 :(得分:1)
您的查询在语法上不正确,所以我的建议也不是,但您会明白:使用ROW_NUMBER
和OVER(PARTITION BY ...)
来获取编号的子集。然后使用CASE
仅在数字为“1”的行中强制所需的值。其他行返回空字符串或NULL
。
注意:我将两个名称相同的primaryid
列更改为ID1
和ID2
:
WITH Numbered AS
(
Select *
,ROW_NUMBER() OVER(PARTITION BY ID1 ORDER BY col2,col3) AS SortNumber
from
(SELECT primaryid AS ID1, col2, col3
from g.table
left join (random stuff)
WHERE DATEPART(m, CreateDateTime) = DATEPART(m, DATEADD(m, -1, getdate()))
AND DATEPART(yyyy, CreateDateTime) = DATEPART(yyyy, DATEADD(m, -1, getdate()))) t1
inner join
(select primaryid AS ID2, col4, col5
from g.table
where primaryid in (select primaryid from g.table) and col5 = 0) t2
on t1.ID1 = t2.ID2
)
SELECT CASE WHEN SortNumber=1 THEN ID1 ELSE '' END AS ID1
,CASE WHEN SortNumber=1 THEN col2 ELSE '' END AS col2
,CASE WHEN SortNumber=1 THEN col3 ELSE '' END AS col3
,ID2,col4,col5
FROM Numbered