~ 列出連續5天有紀錄 ~

| mysql | No Comments

先要create function

DELIMITER //
CREATE FUNCTION bits_find_N1(bits BIGINT, trait BIGINT)
  RETURNS BOOL
  BEGIN
    WHILE bits <> 0 DO
      IF ((bits & trait) = trait) THEN
        RETURN TRUE;
      END IF;
      SET bits = bits >> 1;
    END WHILE;
    RETURN FALSE;
  END//
  DELIMITER ;

mysql statement

SELECT accountname AS bit FROM tablename
WHERE log_date BETWEEN '2012-12-30 00:00:00' AND '2013-01-03 23:59:59'
GROUP BY uid
HAVING bits_find_N1(BIT_OR(1 << datediff(log_date, '2012-12-30')),
b'11111') IS TRUE;

如果某column 數目要到一定數目

SELECT accountname AS bit, sum(cardamount) FROM tablename
WHERE log_date BETWEEN '2012-12-30 00:00:00' AND '2013-01-03 23:59:59'
GROUP BY uid
HAVING bits_find_N1(BIT_OR(1 &lt;&lt; datediff(log_date, '2012-12-30')),
b'11111') IS TRUE and sum(cardamount)&gt;=1200;

詳細可參考

http://www.mysqlops.com/2012/03/06/an_interesting_query.html

トラックバック

このブログ記事に対するトラックバックURL:

コメント & トラックバック

No comments yet.

Comment feed

コメントする

Smiley face

August 2018
S M T W T F S
« Jul    
 1234
567891011
12131415161718
19202122232425
262728293031