我确定这是因为我不知道如何使用LEFT JOIN,但我正在编写一个不返回NULL值的查询。这是查询:
CREATE TABLE #OrgMaster
(OrgName nvarchar(100))
INSERT INTO #OrgMaster (OrgName)
SELECT DISTINCT Organization
FROM StageReleaseCalendar_VW
SELECT SRC.Organization
, SRC.deploytype
, COUNT(SRC.deploytype) AS 'Deployment Count'
, DATEPART(m,SRC.actualstarttime) AS 'MonthNum'
, DATENAME(m,SRC.actualstarttime) AS 'MonthNam'
FROM #OrgMaster TTOM LEFT OUTER JOIN StageReleaseCalendar_VW SRC
ON LEFT(TTOM.OrgName, LEN(TTOM.OrgName)) = SRC.Organization
WHERE DATEDIFF(m, SRC.scheduledstarttime, CURRENT_TIMESTAMP) BETWEEN 1 AND 2
AND completerelease = 1
AND deploytype IN ('Service Pack','Hot Fix')
AND cancelled = 0
GROUP BY SRC.Organization, SRC.deploytype, DATEPART(m,SRC.actualstarttime), DATENAME(m,SRC.actualstarttime)
DROP TABLE #OrgMaster
总共有四个组织:商业,消费者,合作伙伴和销售。创建临时表后,如果我然后运行以下查询:
SELECT OrgName FROM #OrgMaster
结果如下:
商业 消费者 伙伴 销售
合作伙伴在7月或8月没有任何类型的部署,所以我想要得到的是一组结果,包括合作伙伴的四个NULL记录 - 七月份的修补程序记录,八月份的修补程序,用于服务7月打包,8月打包服务。相反,我得到的结果集仅限于部署实际发生的那些条目。
有人能看到我在这里不理解的东西吗?
感谢。
答案 0 :(得分:1)
问题是你的where子句按(右)表中的字段限制数据。这不会给你空值。为此,我经常将SELECT包含在另一个SELECT(嵌套)中,这样我就可以在(右)表中查询空值。
SELECT * FROM (
SELECT a.ID as AID, b.ID as BID from TableA a
LEFT JOIN TableB b
On ....
WHERE ...
) tmp Where BID is null
答案 1 :(得分:0)
正确的查询
SELECT TTOM.OrgName
, SRC.deploytype
, COUNT(SRC.deploytype) AS 'Deployment Count'
, DATEPART(m,SRC.actualstarttime) AS 'MonthNum'
, DATENAME(m,SRC.actualstarttime) AS 'MonthNam'
FROM #OrgMaster TTOM LEFT OUTER JOIN StageReleaseCalendar_VW SRC
ON LEFT(TTOM.OrgName, LEN(TTOM.OrgName)) = SRC.Organization
WHERE SRC.Organization is null or
DATEDIFF(m, SRC.scheduledstarttime, CURRENT_TIMESTAMP) BETWEEN 1 AND 2
AND deploytype IN ('Service Pack','Hot Fix')
AND completerelease = 1
AND cancelled = 0
GROUP BY TTOM.OrgName, SRC.deploytype, DATEPART(m,SRC.actualstarttime), DATENAME(m,SRC.actualstarttime)
另一种选择是使用ISNULL运算符保护WHERE子句中SCR表的所有字段。
答案 2 :(得分:0)
这对你有用。另外,我认为您也可以使用它来获取其他好的信息。
DECLARE @OrgMaster as table(OrgName nvarchar(100),deptype nvarchar(100),MonthNum int,DeploymentCount int)
DECLARE @Loop1 int
DECLARE @Loop2 int
SELECT @Loop1 = 0, @Loop2 = 0
WHILE @Loop1 <> 2
BEGIN
SELECT @Loop1 = @Loop1 + 1, @Loop2 = 0
WHILE @Loop2 <> 2
BEGIN
SET @Loop2 = @loop2 + 1
INSERT INTO @OrgMaster (OrgName,deptype,MonthNum)
SELECT DISTINCT
Organization
,CASE WHEN @Loop1 = 1 THEN 'Service Pack' ELSE 'Hot Fix' END
,DATEPART(m,DATEADD(MONTH, -1 * @Loop2, GETDATE()))
FROM StageReleaseCalendar_VW
END
END
UPDATE @OrgMaster SET
DeploymentCount = (SELECT COUNT(*)
FROM StageReleaseCalendar_VW
WHERE Organization = OrgName
AND deploytype = deptype
AND DATEPART(m,actualstarttime) = MonthNum
)
SELECT * from @OrgMaster where DeploymentCount = 0