在同一查询中选择并插入查询记录

时间:2013-11-11 12:37:30

标签: mysql

SELECT user_id, description, SUM( Credit ) AS cre, SUM( debit ) AS deb, 
CASE WHEN credit > debit
THEN SUM( credit - debit ) 
END AS del, price, created
FROM accounts
WHERE created
BETWEEN  '2013-11-04'
AND  '2013-11-11'
AND description LIKE  '%Amount Earned%'
OR description =  'S'
OR description =  'B'
GROUP BY user_id
  1. 此查询的问题是此查询是根据accounts表中的user_id选择所有记录。我想选择仅创建的记录 BETWEEN'2013-11-04' 和'2013-11-11'
  2. 我想选择这些记录,并且还需要在同一查询中插入记录
  3. 要求:我想通过user_id,Sum(借方)和SUM(Credit)以及Del - >(credit - debit)从上周组中的账户表中选择记录,将Sum和Insert记录放在同一账户表中。

1 个答案:

答案 0 :(得分:2)

insert into (other table ) 
  SELECT user_id, description, SUM( Credit ) AS cre, SUM( debit ) AS deb, 
     CASE WHEN credit > debit
     THEN SUM( credit - debit ) 
  END AS del, price, created
FROM accounts
WHERE 
( created BETWEEN  '2013-11-04' AND  '2013-11-11' )
AND
( description LIKE  '%Amount Earned%'
  OR description =  'S'
  OR description =  'B' )
GROUP BY user_id, created