我需要能够将两列相加并获得另外两列的第一个输入值。
示例表
trans,invoice,email,amount,ticket,date
111,inv-111,pp@gmail.com,15.00,3,"2014-09-13 15:20:12"
125,inv-125,ab@gmail.com,10.00,2,"2014-09-13 15:15:40"
132,inv-132,ab@gmail.com,10.00,2,"2014-09-13 15:17:19"
145,inv-145,ab@gmail.com,5.00,1,"2014-09-13 15:17:52"
199,inv-199,pp@gmail.com,5.00,1,"2014-09-13 15:18:18"
这就是我所得到的:
通过电子邮件从反式组中选择金额(金额)作为金额,金额(票)作为票,反式,发票,电子邮件,最小(日期);
amount,ticket,trans,invoice,email,min(date)
25.00,5,125,inv-125,ab@gmail.com,"2014-09-13 15:15:40"
20.00,4,111,inv-111,pp@gmail.com,"2014-09-13 15:18:18"
期望的结果:我希望发票和反式列从第一个日期开始。
amount,ticket,trans,invoice,email,min(date)
25.00,5,125,inv-125,ab@gmail.com,"2014-09-13 15:15:40"
20.00,4,199,inv-199,pp@gmail.com,"2014-09-13 15:18:18"
答案 0 :(得分:0)
您可以使用substring_index()
/ group_concat()
诀窍来执行此操作:
select sum(amount) as amount, sum(ticket) as ticket,
substring_index(group_concat(trans order by date asc), ',', 1) as trans,
substring_index(group_concat(invoice order by date asc), ',', 1) as invoice,
email,
min(date)
from trans
group by email;
请注意,这会将值放入长字符串中。这通常在实践中有效,但在中间字符串上有大约1000个字符的默认长度。此外,此结果数据类型是字符串而不是数字,这可能会影响trans
列。输出看起来相同,但底层数据类型不同。
答案 1 :(得分:0)
您可以简单地对预先排序的数据执行操作。使用子查询按日期排序,以便获取最小值。
SELECT sum( n.amount ) AS amount, sum( n.ticket ) AS ticket, n.trans, n.invoice, n.email, min( n.date )
FROM (
SELECT *
FROM test
ORDER BY date
) AS n
GROUP BY email
输出:
amount ticket trans invoice email min(n.date)
25 5 125 inv-125 ab@gmail.com 2014-09-13 15:15:40
20 4 199 inv-199 pp@gmail.com 2014-09-13 15:18:18
答案 2 :(得分:0)
您也可以使用自我加入
来完成此操作select
t1.amount,
t1.ticket,
t.email,
t.trans,
t.invoice,
t.date
from test t
join (
select min(date) date,
email,
sum(amount) as amount,
sum(ticket) as ticket
from test
group by email
) t1
on(t.email = t1.email and t.date = t1.date)