0

帐户表

 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,则如果借方大于贷方,则不会添加任何积分。

我希望选择和插入查询应该写成一个查询。

4

2 回答 2

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'; 

演示在http://sqlfiddle.com/#!2/da06e/1

于 2013-11-08T10:37:45.590 回答
0

您可以使用 MySQL 的插入选择语法。

INSERT INTO accounts (col1, col2) SELECT col1, (expr) AS col2 FROM accounts
于 2013-11-08T09:58:36.997 回答