简体   繁体   English

如果联接列中的值为空,则联接两个表并仅在一个表上产生结果

[英]Joining two tables and producing results only on one table when there are null values on joining column

I have table Quota with columns 'Month Number', 'year','Goal' as below 我的表配额为“月数”,“年”,“目标”列,如下所示

在此处输入图片说明

I have other table Sales with columns 'id', 'Sale Date' as below. 我还有其他表Sales,其列为“ id”,“ Sale Date”,如下所示。

在此处输入图片说明

I am joining both the tables on Month and year of 'sales date' from Sales table to 'Month Number' and 'year' from Quota Table to get the results and i am able to get results if i have sales for that particular month and year.Now for the month of may i have no sales so when i join on those columns i am not getting any results from quota table. 我将销售表中“销售日期”的月份和年份与配额表中的“月号”和“年份”都加入表中,以获取结果,并且如果我有该特定月份的销售量,则能够获得结果。 year.Now对于5月我没有任何销售,所以当我加入这些列时,我不会从配额表中得到任何结果。 how can i just display Quota table values if there are no corresponding sales in Sales table? 如果销售表中没有相应的销售,我如何只显示配额表值? I tried left joining but its not displaying any results. 我尝试退出加入,但未显示任何结果。

Like already said, we don't know your desired output. 就像已经说过的,我们不知道您想要的输出。 But by using a left join you should retrieve the records from the quota table. 但是,通过使用左联接,您应该从配额表中检索记录。

declare @quota table (monthnumber int, qyear int, goal int)
insert into @quota values
(2,2017,5),
(3,2017,10),
(4,2017,8),
(5,2017,8),
(6,2017,10)

declare @sales table (id int, salesdate date)
insert into @sales values
(101,'20170321'),
(102,'20170427'),
(103,'20170223'),
(105,'20170427'),
(108,'20170321'),
(109,null),
(111,null)

select q.*
from @quota as q
    left outer join @sales as s
        on year(s.salesdate) = q.qyear and 
           month(s.salesdate) = q.monthnumber

Returns 返回

monthnumber qyear   goal
--------------------------
2           2017    5
3           2017    10
3           2017    10
4           2017    8
4           2017    8
5           2017    8
6           2017    10

You can use month and year of function and do left join as below 您可以使用功能的月份和年份并按如下所示进行左联接

select * from Quota q left join sales s
on q.year = year(s.saledate) and q.MonthNumber = month(s.saledate)

Despite you didn't specify what output you need or your effort so far, I made my attempt anyway and I guess this is what you want: 尽管到目前为止您都没有指定所需的输出或您需要付出的努力,但无论如何我还是做出了尝试,我想这就是您想要的:

SELECT
    Q.*,
    SalesCount = (SELECT COUNT(*) FROM Sales S
        WHERE YEAR(S."Sale Date") = Q.Year AND MONTH(S."Sale Date") = Q.MonthNumber)
FROM Quota Q

And this is the result: 结果如下:

MonthNumber Year       Goal       SalesCount
2           2017       5          1
3           2017       10         2
4           2017       8          2
5           2017       8          0
6           2017       10         0

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

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