选择与列相关的行

时间:2018-11-15 12:27:17

标签: mysql

我有这样的桌子; col1 col2 col3 week a b c 21 a f g 22 c d e 23 a e f 24 f g h 25 a c f 26 f b e 27 我想计算包含'a'且相差1周和2周等的行。 2次相差1周,1次相差0周。 week diff. count 0 1 1 2 2 0 等等。 谢谢,我试图用我的英语不好说清楚。

1 个答案:

答案 0 :(得分:0)

我不确定我是否理解问题。但是,假设:

  • 您要在 any 列(col1,col2,col3)中以“ a”计数的行。
  • 当您说“ 2次相差1周”时,它是2次,因为“ a”连续2周出现:21和22。
  • 以同样的方式,将有3行(因此,有3次),其中有“ 2周的差额”:每周列等于22、24、26的行

然后,以下查询可能会有所帮助:

SELECT 
    ABS(t2.week - t1.week) AS week_difference,
    COUNT(DISTINCT t1.week) AS count      
FROM 
    temp t1, temp t2
WHERE 
    ((t1.col1 = 'a' OR t1.col2 = 'a' OR t1.col3 = 'a') 
    AND (t2.col1 = 'a' OR t2.col2 = 'a' OR t2.col3 = 'a')) 
    AND  ABS(t2.week - t1.week) <= 2
GROUP BY 
    week_difference
ORDER BY 
    week_difference