我有一个现有的SQL查询,我需要为它添加一个连接,这样只有当另一个表中的列的值与join指定的相同时,才会返回此查询的结果。我过去做过加入,但他们总是在简单的查询上。我只是不确定在哪里插入连接,我尝试的一切都有语法问题。用英语我想:
现有的查询...加入另一个表,其中ANOTHERTABLE.COLUMNNAME =“SOMEVALUE”
查询是:
; WITH cte_DateFormat AS (SELECT ServerName, CONVERT(DATE, Date, 103) AS Date, [Capacity(GB)], [Free Space (GB)], Region
FROM [Some_Table]), cte_Rank AS
(SELECT ROW_NUMBER() OVER (PARTITION BY ServerName, CAST(YEAR(Date) AS VARCHAR(4)) + CAST(MONTH(Date) AS VARCHAR(2))
ORDER BY Date DESC) AS ID, Region, ServerName, Date, [Capacity (GB)], [Free Space (GB)]
FROM cte_DateFormat)
SELECT Region, ServerName, Date, [Capacity (GB)], [Free Space (GB)]
FROM cte_Rank
WHERE ID = 1
ORDER BY Date DESC, Region DESC
答案 0 :(得分:2)
听起来你不想加入,你想要求另一个表中存在一个值。所以使用EXISTS:
; WITH cte_DateFormat AS (...) , cte_Rank AS (...)
SELECT Region, ServerName, Date, [Capacity (GB)], [Free Space (GB)]
FROM cte_Rank
WHERE ID = 1
AND EXISTS
(
select *
from anothertable
where anothertable.servername = cte_Rank.ServerName
and ... -- some other criteria if needed
)
ORDER BY Date DESC, Region DESC