2017-09-14 80 views
1

难以让我的头在这一个。SQL Server 2012 - 找到重复的月份(字符串),但不同的年份

我被要求创建一份报告,显示上一年在同一个月注册的客户。

发票表看起来有点像这样:(无法弄清楚如何创建一个更好的表)

invoiceid customerid monthinvoice yearinvoice  
1   50   July   2016* 
2   51   July   2016 
3   52   July   2016* 
4   53   July   2016 
5   54   August   2016 
6   50   July   2017* 
7   51   August   2017 
8   52   July   2017* 
9   53   August   2017 
10   54   September  2017 

使用的唯一正确的日期列是生成发票日期和收到付款日期。

标有*的记录是我唯一感兴趣的记录,我只想看到2个记录,当我将一个月作为参数传递时(我会被要求显示有多少客户在8月份续订如果第一张发票是2016年7月,下一张发票是2017年8月,他们将被视为新客户,而不是续订(必须完全是12个月) 1)50 2)52

任何非常感谢。

+0

格式化一下。我期待看到2条记录,customerid 50和52返回 – user3442107

+0

据我了解你的问题过滤器在月份发票'七月'可能够了吗? –

回答

0

这是一种方式。首先,我们收到本月的所有发票,本年度,然后联盟到上一年的同一个月。然后,我们会过滤使用HAVING的记录的客户。

;with cte as(
select * 
from yourtable 
where 
    (monthinvoice = @monthinvoice 
    and yearinvoice = datepart(year,getdate())) 
union 
select * 
from yourtable 
where 
    (monthinvoice = @monthinvoice 
    and yearinvoice = datepart(year,dateadd(year,-1,getdate())))) 

select * 
from cte 
where customerid in (select customerid from cte group by customerid having count(invoiceid) > 1) 
+1

我打算和这个答案一起去。我用你的逻辑来获得同一月份所有当前和以前年度发票的清单,我只是检查了两个集合中都存在客户ID。谢谢!当你考虑它时,它是非常明显的! – user3442107

-1

如果按照正确的问题林...

SELECT customerid FROM InvTblName T 
    INNER JOIN (SELECT customerID 
      FROM InvTblName  
      HAVING Z.invyear=T.invyear+1) Z 
     ON T.invmonth=Z.invmonth 
+1

这是永远不会工作。 yearinvoice = yearinvoice + 1永远不会成立。我想你忘了使用自我加入。 –

+0

是的,你需要一个单独的子查询 –

0

像这样

select customerid , monthinvoice from yourtable 
where yearinvoice in (2016, 2017) and monthinvoice = 'July' 
group by customerid , monthinvoice 
having count(*) = 2 
+0

你需要一个月的过滤器,这将不会返回所有的列。 – scsimon

+0

是的,你这样做... OP明确表示他们想在一个月内通过以限制数据...... *当我将一个月作为参数传递时* ...并且他们想要返回所有列。在你原来的回答中你陈述了*(没有测试它)*那它是什么? – scsimon

+0

这样然后,嗯?同时我测试了它。 –

0

我想这应该为你 -

SELECT I1.invoiceid, I1.customerid, I1.monthinvoice, I1.yearinvoice, I2.yearinvoice 
FROM Invoice_table I1 
INNER JOIN Invoice table I2 
ON I1.customerid = I2.customerid 
AND I1.monthinvoice = I2.monthinvoice 
AND I1.yearinvoice = I2.yearinvoice + 1 
0

类似下面的应该给你一些想法,如何打造出来的报告做的伎俩。

Declare @ReportYear as int = 2017; 
--this should show all customers with invioices for these months in both 2017 and 2016 
select a.customerid, a.monthinvoice 
from 
(
    --get people with invoice last year 
    Select distinct customerid, monthinvoice 
    from Invoices i0 
    where yearinvoice = @ReportYear - 1 
) a 
join 
(
    --get people with invoice this year 
    Select distinct customerid, monthinvoice 
    from Invoices i0 
    where yearinvoice = @ReportYear 
) b on a.customerid = b.customerid 
     and a.monthinvoice = b.monthinvoice