简体   繁体   English

SQL交叉连接和IIF(ISNULL)-不能按预期工作

[英]SQL Cross Join and IIF(ISNULL) - Not Working as Expected

I'm writing a query with a report file, an employee file and a report distribution file. 我正在用报告文件,员工文件和报告分发文件编写查询。 I would like a list of employee names, each with every report name and a 0 if they don't get the report and a 1 if they do get the report. 我想要一份雇员姓名列表,每个雇员姓名都有每个报告名称,如果他们没有得到报告,则为0,如果他们得到报告,则为1。

 select distinct ut.user_name
      , ut.emailaddress
      , r.name
      , iif(ISNULL(rd.employeeid,0)=0, 0,1) AS currentreport
 from   US_usertable ut 
 cross join DL_reports r
 left outer join DL_Reptdistrib rd 
   on ut.employeeID = rd.employeeid

For each user, I get a complete set of reports - so the cross join works - but either they get a 1 for all the reports or a 0 for all their reports. 对于每个用户,我都有完整的报告集-因此交叉连接有效-但他们要么为所有报告获得1,要么为所有报告获得0。 I don't understand why this query isn't working. 我不明白为什么这个查询无法正常工作。 Kindly help if you can. 如果可以的话,请帮忙。 Thanks in advance!!! 提前致谢!!!

I think you are missing a join condition on the report : 我认为您在报告中缺少加入条件:

select ut.user_name, ut.emailaddress, r.name,
       (case when rd.employeeid is null then 0 else 1 end) as currentreport
from US_usertable ut cross join
     DL_reports r left outer join
     DL_Reptdistrib rd
     on ut.employeeID = rd.employeeid and r.?? = rd.??;

The ?? ?? is for the field used to identify the report. 用于标识报告的字段。 I might guess that it is reportID . 我可能猜到它是reportID

Note: I switched the syntax to standard SQL. 注意:我已将语法切换为标准SQL。 IIF() is in SQL Server for compatibility with MS Access (why Microsoft didn't put the ANSI standard case in MS Access is beyond me). IIF()在SQL Server中是为了与MS Access兼容(为什么Microsoft不在MS Access中使用ANSI标准case超出了我的范围)。 I also replaced ISNULL() with the ANSI standard IS NULL . 我还用ANSI标准IS NULL替换了ISNULL()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM