帐户表
user_id description credit debit created modified
01 Earned 10 0 06-11-2013 06-11-2013
02 Normal 0 1 05-11-2013 05-11-2013
03 Earned 5 0 04-11-2013 04-11-2013
04 Earned 20 0 03-11-2013 03-11-2013
05 Normal 0 1 02-11-2013 02-11-2013
01 Earned 5 0 02-11-2013 02-11-2013
01 Normal 0 1 01-11-2013 01-11-2013
02 Earned 10 0 01-11-2013 01-11-2013
我尝试了以下查询:
SELECT SUM(CASE WHEN description LIKE '%Earned%'
THEN Credit
ELSE 0
END ) as cre, SUM(debit) as deb FROM accounts
WHERE created is between '$Monday' AND '$Sunday'
INSERT into accounts (user_id, description, credit, debit, created, modified)
VALUES ( 'user_id', 'Removed Free Earned', 'cre', 'deb', Now(), Now());
我想根据用户选择账户表和汇总信用卡和汇款借方,例如,如果user_id 01总信用额为10,则上周一至周日的借方总金额 是3然后应在“deb”的“插入查询”位置添加7个点。但如果总信用额度为10且总借方为20,那么如果借方大于贷方,则不会增加任何积分。
我希望Select和Insert Query应该写成一个查询。
答案 0 :(得分:2)
您可以使用以下查询
INSERT into newaccounts (user_id, description, credit, debit, created, modified)
SELECT user_id,description,
SUM(CASE WHEN
description = 'Earned'
THEN credit
ELSE 0
END) cre,
SUM(debit) as deb,NOW(),NOW()
FROM accounts
WHERE created between '03-11-2013' AND '04-11-2013';
演示
答案 1 :(得分:0)
您可以使用MySQL的insert select语法。
INSERT INTO accounts (col1, col2) SELECT col1, (expr) AS col2 FROM accounts