0

我需要对下表进行查询,其输出如下所述

我有列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)值,如果这三个是,那么我需要得到最后一个好的值日期(在 A 列的情况下,输出应该是“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之间的值)...请帮助

4

1 回答 1

1

如果不同的列对“好价值”有不同的标准,我只需依次查询每一列,然后将UNION它们放在一起

例如

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 )
于 2013-07-29T10:11:05.253 回答