S
S
Seilordp2014-03-12 14:16:17
SQL
Seilordp, 2014-03-12 14:16:17

Sql query - how to display active referrals?

Good afternoon! I ask for help, because I can not solve such a request myself.
There is a table like:
| id | name | param1 | param2 | param 3 | ref_id |
So, you need to display the names in descending order of the number of active referrals, those who have param1 + param 2 + param 3 > 5 are considered, and also the id of this person is in ref_id.
Thanks in advance.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
A
Alexander Litvinov, 2014-03-12
@Seilordp

For all refs

SELECT `t1`.`id`, `t1`.`name`, COUNT(`t2`.`id`) AS cnt 
FROM `table` as `t1`
LEFT JOIN `table` `t2` ON `t1`.`id` = `t2`.`ref_id`
WHERE (`t1`.`param1` + `t1`.`param2` + `t1`.`param3`) > 5 
GROUP BY `t1`.`id`
ORDER BY cnt DESC

For refs with param1 + param 2 + param 3 > 5
SELECT `t1`.`id`, `t1`.`name`, COUNT(`t2`.`id`) AS cnt 
FROM `table` as `t1` 
LEFT JOIN `table` `t2` ON `t1`.`id` = `t2`.`ref_id` 
AND (`t2`.`param1` + `t2`.`param2` + `t2`.`param3`) > 5 
WHERE (`t1`.`param1` + `t1`.`param2` + `t1`.`param3`) > 5 
GROUP BY `t1`.`id` ORDER BY cnt DESC

A
Alexander, 2014-03-12
@Papagatto

select name from table 
where sum(param1+param2+param3)>5 as s 
  and ref_id = 'id данного человека'
order by s desc

A
Alexander Litvinov, 2014-03-12
@Sander_Li

SELECT `name`,  (`param1` + `param2` + `param3`) AS s FROM `table` WHERE `ref_id` = 5 HAVING s > 5 ORDER BY s DESC

A
Alexander, 2014-03-12
@Papagatto

WITH CTE (name, summa,ref_id)
AS
(
    SELECT name, param1+param2+param3, ref_id
    FROM table1    
)

SELECT name
FROM CTE
where summa>5 
  and ref_id = 1
order by summa desc

Here is the request

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question