我从这个数据库中获取值。我需要按sim_id排序的总request_amount,其中username由user_name和parents彼此相关。例如Alam=>Shimul
,Shimul=>Shihab
,Shihab=>Khaled
等等......然后当我只搜索user_name='Alam'
时所有user_name
的主要父母时,那么输出将跟随....
数据表user_request
user_name sim_id request_amount request_date parents
Alam 1 98 2014-01-11 Admin
Shimul 2 100 2014-01-11 Alam
Shihab 3 50 2014-01-11 Shimul
Khaled 2 20 2014-01-11 Shihab
Sumon 3 100 2014-01-11 Shihab
输出
user_name sim_id1 sim_id2 sim_id3 total
Alam 98 0 0 98
Shimul 0 100 0 100
Shihab 0 0 50 200
Khaled 0 20 0 20
Sumon 0 0 100 100
请有人帮我解决问题......
答案 0 :(得分:0)
像这样的东西,使用SUM但在SUM中有一个IF: -
SELECT user_name,
SUM(IF(sim_id = 1, request_amount, 0)) AS sim_id1,
SUM(IF(sim_id = 2, request_amount, 0)) AS sim_id2,
SUM(IF(sim_id = 3, request_amount, 0)) AS sim_id3,
SUM(sim_id) AS total
FROM user_request
GROUP BY user_name