1

大家好,我再次需要帮助:D

就像这样我需要找到最大常数值或最大计数值,例如我有

ClientID   YEAR      МОNTH
1          2013        1    
1          2013        2  
1          2013        3 
1          2013        4  
1          2013        5  
1          2013        6  
1          2013        7  
1          2013        8  
1          2013        9  
1          2013       10  
1          2013       11  
1          2013       12  
2          2013        1    
2          2013        2  
2          2013        3 
2          2013        4    
2          2013        6  
2          2013        7  
2          2013        8   
2          2013       10  
2          2013       11  
2          2013       12  

如果我做

select clientID,year, max(month) from table where client id =1

select clientID,year, max(month) from table where client id =2

然后我得到

ClientID   YEAR      МОNTH
    1      2013        12
    2      2013        12

有没有办法选择直到第一个缺失的月份?像

ClientID   YEAR      МОNTH
    1      2013        12
    2      2013        4

提前 TNX

4

2 回答 2

1

这应该这样做:

SELECT ClientID, YEAR, MIN(MONTH)
FROM table
WHERE NOT EXISTS (SELECT * 
    FROM table c 
    WHERE c.MONTH = table.MONTH + 1 
        AND c.ClientID = table.ClientID
        AND c.YEAR = table.YEAR)
GROUP BY ClientID, YEAR

这会查找恰好在间隙之前的所有条目,然后为具有多个结果的任何组合取ClientID最小值YEAR

SQLFiddle

于 2013-11-07T13:43:12.380 回答
0
select clientid,year,max(month) from [dbo].[24] where id <(


SELECT TOP 1 t1.month+1 
FROM [dbo].[24] t1
WHERE NOT EXISTS(SELECT * FROM [dbo].[24] t2 WHERE t2.month = t1.month + 1)
ORDER BY t1.month
)

group by clientid,year
于 2013-11-07T13:24:33.173 回答