mysql 数据库中有一张 交易记录表,存储过程中想通过count函数查出30天内的交易数、60天的交易数

mysql 数据库中有一张 交易记录表,存储过程中想通过count函数查出30天内的交易数、60天的交易数,第1张

可直接用嵌套查询。

方法如下:

如数据:

id name

1a

1b

2c

2d

3e

3f

3g

3h

select count(t.counts) from

(select id,count(*) counts from 表名 group by id) t

这样得到的结果就是3。

为这个问题 专门写了一个mysql function,实现的功能是,返回前几条记录。其实还可以在完善的,返回这些记录的数据的。

delimiter $$

drop function if exists top7$$

create function top7(num int(11))

returns int(11)

begin

declare totalPrice int

declare i int

declare countNum int

declare tmp int

select count(1) into countNum from mywcd

set i=0

set totalPrice=0

set tmp=0

tt:

while i<countNum

do

set tmp=(select price from mywcdlimit i,1)

set i=i+1

set totalPrice=totalPrice+tmp

if totalPrice>=num then

leave tt

end if

end while

return i

end

$$

delimiter

mysql>select * from mywcd

+—-+——-+

| id | price |

+—-+——-+

| 1 | 100 |

| 2 | 200 |

| 3 | 300 |

| 4 | 400 |

| 5 | 500 |

| 6 | 600 |

+—-+——-+

6 rows in set (0.00 sec)

这是我测试数据的表全部记录。

调用以及返回结果:

mysql>select top7(1001)

+————+

| top7(1001) |

+————+

| 5 |

+————+

1 row in set (0.00 sec)

余额可以单独用一个余额记录表,这样如果要查询每次消费记录的时候,也能查出来每次消费后还有多少余额。余额记录表里面主要是三个字段:用户账号、每次消费后的余额、时间点。

CREATE TABLE account

(

id integer NOT NULL DEFAULT nextval('trade_id_seq'::regclass),

no character varying(10) NOT NULL, -- 账号

balance money NOT NULL DEFAULT 0.00, -- 余额

datetime timestamp without time zone NOT NULL DEFAULT (now())::timestamp(0) without time zone,

CONSTRAINT account_pkey PRIMARY KEY (id)

)

通过每次的余额变化就知道每次消费后的余额情况

select acc.*, (select sum(balance)+acc.balance from account as ac where ac.id <acc.id) as profit from account as acc

id | no | balance | datetime | profit

----+------+----------+---------------------+---------

1 | 1000 |$0.00 | 2013-10-09 10:51:10 |

2 | 1000 | $12.60 | 2013-10-09 10:51:22 | $12.60

4 | 1000 | $16.80 | 2013-10-09 10:51:42 | $29.40

5 | 1000 | $100.00 | 2013-10-09 10:51:49 | $129.40

6 | 1000 | $200.00 | 2013-10-09 10:56:35 | $329.40

7 | 1000 | $50.45 | 2013-10-09 10:57:23 | $379.85

8 | 1000 | $75.50 | 2013-10-09 10:57:31 | $455.35

9 | 1000 | -$55.30 | 2013-10-09 10:59:28 | $400.05

10 | 1000 | -$200.00 | 2013-10-09 10:59:44 | $200.05

(9 rows)


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/8572801.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-04-18
下一篇2023-04-18

发表评论

登录后才能评论

评论列表(0条)

    保存