基于不同输入参数的最大日期

时间:2014-09-30 20:27:16

标签: sql

有谁能让我知道我在这里失踪了什么?

SELECT    fld1,   fld2,    fld3, 
MAX(DATE)    OVER     (PARTITION    BY    fld1,    fld2,    fld3)
FROM table1 where fld1 = userinput1 and Fld2 = userinput2 and Fld3 = userinput3

当用户输入userinput1,userinput2和userinput3时,我希望基于该组合的最大日期。
当用户只输入userinput1和userinput3时,我希望基于该组合的最大日期:userinput1,userinput2。
当用户仅输入userinput3时,我希望基于该unerinput3的最大日期。

实际上它可以是任何组合

Table1  has

Fld1    fld2   fld3   date

1         a     A      01/01/2014
1         a     A      01/02/2014
1         a     B      01/03/2014
1         b     C      01/04/2014
1         b     C      01/05/2014
1         c     D      01/06/2014
2         a     A      01/07/2014


userinput1  = 1
unerinput2  = a
userinput3  = A

Max Date should be  01/02/2014


userinput1  = 1
unerinput2  = a
userinput3  = user doesn’t enter anything

Max Date should be 01/03/2014


userinput1  = 1
unerinput2  = user doesn’t enter anything
userinput3  = user doesn’t enter anything

Max Date should be 01/06/2014



userinput1  = user doesn’t enter anything
unerinput2  = user doesn’t enter anything
userinput3  = user doesn’t enter anything


Max Date should be  01/07/2014

提前致谢 拉姆

1 个答案:

答案 0 :(得分:0)

您没有指定您正在使用的数据库(您应该经常这样做),所以我假设MS SQL Server。

如果您只想要max(日期)并且对其他列感兴趣,我认为这段代码应该有用(除非我完全误解了你想要的内容):

DECLARE @userinput1 int = 1
DECLARE @userinput2 char = 'a' 
DECLARE @userinput3 char = 'A'

SELECT MAX(DATE)
FROM Table1 
WHERE 
    fld1 = CASE WHEN @userinput1 IS NULL THEN fld1 ELSE @userinput1 END
    AND
    fld2 = CASE WHEN @userinput2 IS NULL THEN fld2 ELSE @userinput2 END
    AND
    fld3 = CASE WHEN @userinput3 IS NULL THEN fld3 ELSE @userinput3 END

这里有一个sample SQL Fiddle,显示了带有不同变量组合的输出。