显示与日期年序列不匹配的记录

时间:2015-01-05 14:30:22

标签: sql sql-server

如何与日期年序列不匹配的记录 我试图返回所有未按年订购的客户记录。

例如,

cust1 - 2010
cust1 - 2012
cust1 - 2013
cust1 - 2014
cust2 - 2014

正如您所见,cust1尚未在2011年订购

我想返回显示cust1的行。

我需要能够指定一系列日期,例如最小和最大。

我试过这个:

DECLARE @MINDATE AS INT;
SELECT @MINDATE = '2010';

DECLARE @MAXDATE AS INT;
SELECT @MAXDATE = '2014';

SELECT CUSTID, YEAR(DATE) AS [YEAR]
FROM ORDER
WHERE DATE BETWEEN @MINDATE AND @MAXDATE;

4 个答案:

答案 0 :(得分:1)

您可以指定如下序列:

DECLARE
    @MINYEAR AS INT = '2010',
    @MAXYEAR AS INT = '2014';

with base as
(
    select @MINYEAR [year]
    union all
    select [year] + 1
    from base
    where [year] < @MAXYEAR
)
select * from [base]

结果:

year
----
2010
2011
2012
2013
2014

Ant然后JOIN与你的表格,例如:

DECLARE
    @MINYEAR AS INT = '2010',
    @MAXYEAR AS INT = '2014';

with base as
(
    select @MINYEAR [year]
    union all
    select [year] + 1
    from base
    where [year] < @MAXYEAR
)
select y.[year], isnull(b.CUSTID, 'No data') [CUSTID]
from base y
left join ORDER b on YEAR(b.DATE) = y.[year]

我不知道如何实现所需的输出,因为您没有提供任何数据架构

答案 1 :(得分:0)

SELECT      #sequence.value
FROM        #sequence
LEFT JOIN   MyTable ON #sequence.value = MyTable.value
WHERE       MyTable.value IS NULL

取自answer

答案 2 :(得分:0)

我倾向于使用count(distinct)执行此操作:

SELECT CUSTID
FROM ORDER
WHERE DATE BETWEEN @MINDATE AND @MAXDATE
GROUP BY CUSTID
HAVING COUNT(DISTINCT YEAR(DATE)) = (SELECT COUNT(DISTINCT YEAR(DATE))
                                              FROM ORDER
                                              WHERE DATE BETWEEN @MINDATE AND @MAXDATE
                                             );

编辑:这假设所有年份都在数据中表示。

答案 3 :(得分:0)

试试这个,它会报告所有年份都没有订单的客户。

它将客户的不同年份数与根据MaxDate和MinDate之间的差异应该存在的年数进行比较。

SELECT CUSTID
FROM ORDER
WHERE DATE BETWEEN @MINDATE AND @MAXDATE
GROUP BY CUSTID
HAVING COUNT(DISTINCT YEAR(DATE)) <> (YEAR(@MAXDATE) - YEAR(@MINDATE)) + 1