比较SQL计算值的差异行

时间:2014-04-17 08:32:32

标签: mysql sql

我有一张桌子:

id     firstval    secondval     
1         4            5
2         5            4
3         3            3
4         6            6
5         7            8
6         9            8
7         3            3
8         3            3

我需要做的第一件事是计算secondval > firstval的次数。这显然没问题。

然而,我正在努力的是如何计算下一行满足条件secondval > firstval

的次数(对于secondval < firstval的每个实例)

所以在这个例子中有两行可以满足第一个规则id 1&amp; 5和2为第二个规则,下一行是id 2和6.

3 个答案:

答案 0 :(得分:2)

SELECT id, @prevGreater AND secondval < firstval AS discrepancy, 
       @prevGreater := secondval > firstval AS secondGreater
FROM (SELECT * FROM YourTable ORDER BY id) AS x
CROSS JOIN (SELECT @prevGreater := false) AS init

DEMO

答案 1 :(得分:0)

SELECT * from table t1
INNER JOIN table t2 on t1.ID+1=t2.ID -- here we join on t2.ID is t1.ID+1
WHERE t1.secondval>t1.firstval AND t2.secondval<t2.firstval

现在您可以根据需要使用COUNT语句:)

答案 2 :(得分:0)

DECLARE @YourTable TABLE 
(id int, firstval int, secondval int)

INSERT INTO @YourTable
SELECT 1, 4, 5
UNION ALL
SELECT 2, 5, 4
UNION ALL
SELECT 3, 3, 3
UNION ALL
SELECT 4, 6, 6
UNION ALL
SELECT 5, 7, 8
UNION ALL
SELECT 6, 9, 8
UNION ALL
SELECT 7, 3, 3
UNION ALL
SELECT 8, 3, 3

SELECT  ID
,CASE 
    WHEN SECONDVAL>FIRSTVAL THEN 0
    WHEN FIRSTVAL>SECONDVAL THEN 1
    ELSE 0
END AS DISCREPANCY
,CASE 
    WHEN SECONDVAL>FIRSTVAL THEN 1
    WHEN FIRSTVAL>SECONDVAL THEN 0
    ELSE 0
END AS SECONDGREATER

FROM    @YourTable

你可以试试这个。