0

There are 3 different tables and from first table i get the "contact_id" and based on this i would like to do the SUM into the next 2 tables and then MINUS the tables as in the code bellow.
I am trying to use the result "contact_id" from the first query into the following queries

SELECT ( SELECT `id` FROM `civicrm_contact` WHERE `first_name` LIKE 'test2' ) AS contact_id 

=============================================================

SELECT ( SELECT SUM(`total_amount`) FROM `civicrm_contribution` WHERE `contact_id`= ) - ( SELECT SUM(`fee_amount`) FROM `civicrm_participant` WHERE `contact_id`= ) As RemainingPoints 

4 Answers 4

1

You need to use subquery :

SELECT ( SELECT SUM(`total_amount`) FROM `civicrm_contribution` WHERE `contact_id`= (SELECT `id` FROM `civicrm_contact` WHERE `first_name` LIKE 'test2' ) AS contact_id) ) - ( SELECT SUM(`fee_amount`) FROM `civicrm_participant` WHERE `contact_id`= (SELECT `id` FROM `civicrm_contact` WHERE `first_name` LIKE 'test2' ) AS contact_id) ) As RemainingPoints 
Sign up to request clarification or add additional context in comments.

2 Comments

The query may fail as the inner sub query can return more than one value. Use in instead of =
In this Case let's to use LIMIT 1.
0

This should solve your problem :

SELECT ( SELECT SUM(`total_amount`) FROM `civicrm_contribution` WHERE `contact_id` in (SELECT `id` FROM `civicrm_contact` WHERE `first_name` LIKE 'test2' ) AS contact_id) ) - ( SELECT SUM(`fee_amount`) FROM `civicrm_participant` WHERE `contact_id` in (SELECT `id` FROM `civicrm_contact` WHERE `first_name` LIKE 'test2' ) AS contact_id) ) As RemainingPoints 

1 Comment

Thanks for your elaborated answer! I finally changed the structure and I used sub select in my query. thanks for the distinct hint which I did not know.
0

You should limit the result of the subquery to 1 otherwise it will result in an error, the best way is to match the name using '=' instead of 'like'

SELECT ( SELECT SUM(`total_amount`) FROM `civicrm_contribution` WHERE `contact_id`= (SELECT `id` FROM `civicrm_contact` WHERE `first_name` LIKE 'test2' limit 1 ) AS contact_id) ) - ( SELECT SUM(`fee_amount`) FROM `civicrm_participant` WHERE `contact_id`= (SELECT `id` FROM `civicrm_contact` WHERE `first_name` LIKE 'test2' limit 1 ) AS contact_id) ) As RemainingPoints 

Comments

0

This could help you

SELECT @s:=1+1 ,@s + 4,@s-1 

o/p -@s:=1+1|@s + 4 | @s-1

 2 | 6| 1 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.