I have a union of three tables (t1, t2, t3).
Each rerun exactly the same number of records, first column is id, second amount:
1 10
2 20
3 20
1 30
2 30
3 10
1 20
2 40
3 50
Is there a simple way in SQL to sum it up, i.e. to only get:
1 60
2 80
3 80
select id, sum(amount) from (
select id,amount from table_1 union all
select id,amount from table_2 union all
select id,amount from table_3
) x group by id
SELECT id, SUM(amount) FROM
(
SELECT id, SUM(amount) AS `amount` FROM t1 GROUP BY id
UNION ALL
SELECT id, SUM(amount) AS `amount` FROM t2 GROUP BY id
) `x`
GROUP BY `id`
I groupped each table and unioned because i think it might be faster, but you should try both solutions.
Subquery:
SELECT id, SUM(amount)
FROM ( SELECT * FROM t1
UNION ALL SELECT * FROM t2
UNION ALL SELECT * FROM t3
)
GROUP BY id
Not sure if MySQL uses common table expression but I would do this in postgres:
WITH total AS(
SELECT id,amount AS amount FROM table_1 UNION ALL
SELECT id,amount AS amount FROM table_2 UNION ALL
SELECT id,amount AS amount FROM table_3
)
SELECT id, sum(amount)
FROM total
I think that should do the trick as well.
As it's not very clear from previous answers, remember to give aliases (on MySQL/MariaDb) or you'll get error:
Every derived table must have its own alias
select id, sum(amount) from (
select id,amount from table_1 union all
select id,amount from table_2 union all
select id,amount from table_3
) AS 'aliasWhichIsNeeded'
group by id
Yes!!! Its okay! Thanks!!!!
My code finishing:
SELECT SUM(total)
FROM (
(SELECT 1 as id, SUM(e.valor) AS total FROM entrada AS e)
UNION
(SELECT 1 as id, SUM(d.valor) AS total FROM despesa AS d)
UNION
(SELECT 1 as id, SUM(r.valor) AS total FROM recibo AS r WHERE r.status = 'Pago')
) x group by id
SELECT BANKEMPNAME, workStation, SUM (CALCULATEDAMOUNT) FROM(
SELECT BANKEMPNAME, workStation, SUM(CALCULATEDAMOUNT) AS CALCULATEDAMOUNT,SALARYMONTH
FROM dbo.vw_salaryStatement
WHERE (ITEMCODE LIKE 'A%')
GROUP BY BANKEMPNAME,workStation, SALARYMONTH
union all
SELECT BANKEMPNAME, workStation, SUM(CALCULATEDAMOUNT) AS CALCULATEDAMOUNT,SALARYMONTH
FROM dbo.vw_salaryStatement
WHERE (ITEMCODE NOT LIKE 'A%')
GROUP BY BANKEMPNAME, workStation, SALARYMONTH) as t1
WHERE SALARYMONTH BETWEEN '20220101' AND '20220131'
group by BANKEMPNAME, workStation
order by BANKEMPNAME asc
IN MSSQL You can write this way, But Doing UNION ALL THE Column should be the same for both ways.
I have given this example So that you can understand the process...
SL is the primary key.
Table name -> impo
I want to sum all the QTY which have same Model number.(Here add 40+35 because of INDO666)
I tried this:
SELECT i.Model_num, i.QTY
FROM impo AS i
JOIN (SELECT Model_num, SUM(QTY) AS t_qty
FROM impo
GROUP BY Model_num )
AS s ON i.Model_num = s.Model_num
I don't understand why you have an extra join. The subquery seems to do what you want:
SELECT Model_num, SUM(QTY) AS t_qty
FROM impo
GROUP BY Model_num ;
Sum of a multiplication of two columns grouped by another column in an inner join of three tables returns wrong value.
Below are my three tables:
Table1:
Table2:
Table3:
My Query is as below:
SELECT c.price, c.quantity, SUM( c.quantity * c.price ) AS price,
group_concat( a.rate
SEPARATOR '<br>' ) AS rates, c.hsn AS hsn
FROM tax_wa a
INNER JOIN tax_rate_class b ON a.tax_rate_id = b.tax_rate_id
INNER JOIN inv_item c ON b.tax_class_id = c.tax_class_id
WHERE c.invoice_id = '17'
GROUP BY c.hsn
And the result is:
But above one is not correct... To expain it, if you run the below query on the inv_item table (alone, with no joins) you get correct results:
SELECT price, quantity, sum( quantity * price )
FROM `inv_item`
WHERE invoice_id = '17'
GROUP BY hsn
Result is good:
Above result the wrong value calculated
if you add all
Presumably, you want the sum():
SELECT SUM(c.price), SUM(c.quantity), SUM( c.quantity * c.price ) AS price,
group_concat( a.rate SEPARATOR '<br>' ) AS rates, c.hsn AS hsn
FROM tax_wa a INNER JOIN
tax_rate_class b
ON a.tax_rate_id = b.tax_rate_id INNER JOIN
inv_item c
ON b.tax_class_id = c.tax_class_id
WHERE c.invoice_id = 17
GROUP BY c.hsn;
I have two tables in db
1- i want to select distinct value from 2 tables
2- i want to print the number of each value
Ex: if i have on t1
t1
--------------
a
a
a
b
t2:
t2
--------------
a
b
c
the result will be:
a (4)
b (2)
c (1)
i try this but it not what i want
$sql=mysqli_query($conn,"select db_shopname from tbl_order UNION
SELECT db_shopname FROM tbl_item order by db_shopname asc")
or die(mysqli_error($conn));
$count=mysqli_num_rows($sql);
while($res=mysqli_fetch_array($sql)){
echo $res['db_shopname'];echo $count ;echo"<br/>";
}
You need UNION ALL instead of UNION. That way you merge the values from 2 tables into 1 virtual table. Then you can count the number of individual values using GROUP BY clause. Example:
select f, COUNT(f) as countf FROM
(select t1.f from t1 union all select t2.f from t2) t
GROUP BY f
SQL Fiddle
In PHP you can then use $res['countf'] to print the count
try this one :
select a.t1,count(a.t1) as cnt from(select t1 from t1 UNION all
select t2 as t1 from t2 )a group by a.t1
Not sure if the title explains the situation right but I will try to do my best explaining here.
I have a table with 3 fields linked to other tables and I want to get all the Rows grouped in the following way:
item_id, user_id, group_id
1 2 3
2 2 3
3 4 5
4 2 4
In my query i want in comma separated format all the items_id grouped by group_id i also have some extra conditions on the WHERE clause that's why the inner join
That i can do like with this query
"SELECT
GROUP_CONCAT( DISTINCT A.item_id ) AS ids
FROM tableA A
INNER JOIN tableB B ON(tableA.id = tableB.id)
WHERE xxxxx
GROUP BY A.group_id
"
Later i can loop the results and using the comma separated to inner loop every id within the result
But i also want to group it by user_id in order to do something like this
foreach( query_results.... ){
foreach( group_id.... ){
foreach( item_id.... ){
// Display info
}
}
}
Any ideas on this?
using subqueries, we can get both itemids, userids as two seperate columns
select T1.group_id, T1.itemids, T2.userids
FROM
(SELECT group_id,
GROUP_CONCAT( DISTINCT A.item_id ) AS itemids
FROM table1 A
group by group_id) T1
INNER JOIN
(
SELECT
group_id, GROUP_CONCAT( DISTINCT A.user_id ) AS userids
FROM table1 A
group by group_id
) T2
on T1.group_id = T2.group_id
Use 2 GROUP_CONCATS
SELECT GROUP_CONCAT( DISTINCT A.item_id ) AS ids,
GROUP_CONCAT( DISTINCT A.group_id ) AS groups
FROM tableA A
INNER JOIN tableB B ON(tableA.id = tableB.id)
WHERE xxxxx
GROUP BY A.group_id
Loop your resource then use Explode on the groups and ids value and loop them both as you want