使用SQL查询根据条件获取最后的好值?

时间:2013-07-29 09:45:47

标签: sql sql-server sql-server-2008 plsqldeveloper

我需要在下表中查询输出,如下所述

我有列Timestamp, A, B, C, D 并且,样本数据如下

 Timestamp       A   B    C   D
------------------------------
20-7-2013:2:15   1  360   1  -5
20-7-2013:7:15   2  360   E  -3
21-7-2013:9:15   N  360   E  -6
21-7-2013:10:15  N  360   E  -8
22-7-2013:11:15  N  360   E  -7

首先,我需要检查列A最后一个记录值是(NULL or E or -ve)值,如果这三个中的任何一个是肯定的,那么我需要得到最后一个好的值日期(在这种情况下)输出应为“20-7-2013:7:15”的列取决于条件(每列之间0到360之间,> 0,-5到+5)。对于列A到Z,必须进行相同的操作。最终输出应为

ColumnName      Time
------------------------- 
    A      20-7-2013:7:15

更新:对于A列,输出应为:20-7-2013:7:15(因为它是来自最后一个NULL的即时良好值);列B可以忽略,因为最后一个值是360并且它满足条件;对于C列,输出应为:20-7-2013:2:15,因为条件是E错误之前的最后一个好的值,D列输出应该是20-7-2013:7:15,因为它满足条件(值介于-5和+5之间)...请帮助

1 个答案:

答案 0 :(得分:1)

如果不同的列具有不同的“良好价值”标准,我只会依次查询每个列,并UNION将它们放在一起

e.g。

SELECT TOP 1 'A' AS ColumnName, Timestamp AS [Time] FROM <table>
WHERE A IS NOT NULL AND ISNUMERIC(A) = 1 AND A >= 0
ORDER BY Timestamp DESC
UNION
SELECT TOP 1 'B', Timestamp FROM <table>
WHERE B IS NOT NULL AND ISNUMERIC(B) = 1 AND B BETWEEN 0 AND 360 
ORDER BY Timestamp DESC
UNION
...

<强>更新 从下面的评论中,我想我明白这里发生了什么。 听起来每个列都有一些条件需要检查,如果最终日期满足条件,也应该排除。我建议围绕UNION列查询进行外部查询,以删除最后一个值满足的情况。

更新2

SELECT * FROM (
    SELECT TOP 1 'A' AS ColumnName, Timestamp AS [Time] FROM <table>
    WHERE A IS NOT NULL AND ISNUMERIC(A) = 1 AND A BETWEEN 0 AND 360
    ORDER BY Timestamp DESC
    UNION
    SELECT TOP 1 'B', Timestamp FROM <table>
    WHERE B IS NOT NULL AND ISNUMERIC(B) = 1 AND B > 0
    ORDER BY Timestamp DESC
    UNION
    SELECT TOP 1 'C', Timestamp FROM <table>
    WHERE C IS NOT NULL AND ISNUMERIC(C) = 1 AND C BETWEEN -5 AND 5
    ORDER BY Timestamp DESC
    UNION
    SELECT TOP 1 'D', Timestamp FROM <table>
    WHERE D IS NOT NULL AND ISNUMERIC(D) = 1 AND D BETWEEN -5 AND 5
    ORDER BY Timestamp DESC
) Cols
WHERE [Time] < ( SELECT TOP 1 Timestamp FROM <table> ORDER BY Timestamp DESC )