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...
Related
I am wondering how to write this query.
I know this actual syntax is bogus, but it will help you understand what I want.
I need it in this format, because it is part of a much bigger query.
SELECT distributor_id,
COUNT(*) AS TOTAL,
COUNT(*) WHERE level = 'exec',
COUNT(*) WHERE level = 'personal'
I need this all returned in one query.
Also, it need to be in one row, so the following won't work:
'SELECT distributor_id, COUNT(*)
GROUP BY distributor_id'
You can use a CASE statement with an aggregate function. This is basically the same thing as a PIVOT function in some RDBMS:
SELECT distributor_id,
count(*) AS total,
sum(case when level = 'exec' then 1 else 0 end) AS ExecCount,
sum(case when level = 'personal' then 1 else 0 end) AS PersonalCount
FROM yourtable
GROUP BY distributor_id
One way which works for sure
SELECT a.distributor_id,
(SELECT COUNT(*) FROM myTable WHERE level='personal' and distributor_id = a.distributor_id) as PersonalCount,
(SELECT COUNT(*) FROM myTable WHERE level='exec' and distributor_id = a.distributor_id) as ExecCount,
(SELECT COUNT(*) FROM myTable WHERE distributor_id = a.distributor_id) as TotalCount
FROM (SELECT DISTINCT distributor_id FROM myTable) a ;
EDIT:
See #KevinBalmforth's break down of performance for why you likely don't want to use this method and instead should opt for #Taryn♦'s answer. I'm leaving this so people can understand their options.
SELECT
distributor_id,
COUNT(*) AS TOTAL,
COUNT(IF(level='exec',1,null)),
COUNT(IF(level='personal',1,null))
FROM sometable;
COUNT only counts non null values and the DECODE will return non null value 1 only if your condition is satisfied.
Building on other posted answers.
Both of these will produce the right values:
select distributor_id,
count(*) total,
sum(case when level = 'exec' then 1 else 0 end) ExecCount,
sum(case when level = 'personal' then 1 else 0 end) PersonalCount
from yourtable
group by distributor_id
SELECT a.distributor_id,
(SELECT COUNT(*) FROM myTable WHERE level='personal' and distributor_id = a.distributor_id) as PersonalCount,
(SELECT COUNT(*) FROM myTable WHERE level='exec' and distributor_id = a.distributor_id) as ExecCount,
(SELECT COUNT(*) FROM myTable WHERE distributor_id = a.distributor_id) as TotalCount
FROM myTable a ;
However, the performance is quite different, which will obviously be more relevant as the quantity of data grows.
I found that, assuming no indexes were defined on the table, the query using the SUMs would do a single table scan, while the query with the COUNTs would do multiple table scans.
As an example, run the following script:
IF OBJECT_ID (N't1', N'U') IS NOT NULL
drop table t1
create table t1 (f1 int)
insert into t1 values (1)
insert into t1 values (1)
insert into t1 values (2)
insert into t1 values (2)
insert into t1 values (2)
insert into t1 values (3)
insert into t1 values (3)
insert into t1 values (3)
insert into t1 values (3)
insert into t1 values (4)
insert into t1 values (4)
insert into t1 values (4)
insert into t1 values (4)
insert into t1 values (4)
SELECT SUM(CASE WHEN f1 = 1 THEN 1 else 0 end),
SUM(CASE WHEN f1 = 2 THEN 1 else 0 end),
SUM(CASE WHEN f1 = 3 THEN 1 else 0 end),
SUM(CASE WHEN f1 = 4 THEN 1 else 0 end)
from t1
SELECT
(select COUNT(*) from t1 where f1 = 1),
(select COUNT(*) from t1 where f1 = 2),
(select COUNT(*) from t1 where f1 = 3),
(select COUNT(*) from t1 where f1 = 4)
Highlight the 2 SELECT statements and click on the Display Estimated Execution Plan icon. You will see that the first statement will do one table scan and the second will do 4. Obviously one table scan is better than 4.
Adding a clustered index is also interesting. E.g.
Create clustered index t1f1 on t1(f1);
Update Statistics t1;
The first SELECT above will do a single Clustered Index Scan. The second SELECT will do 4 Clustered Index Seeks, but they are still more expensive than a single Clustered Index Scan. I tried the same thing on a table with 8 million rows and the second SELECT was still a lot more expensive.
For MySQL, this can be shortened to:
SELECT distributor_id,
COUNT(*) total,
SUM(level = 'exec') ExecCount,
SUM(level = 'personal') PersonalCount
FROM yourtable
GROUP BY distributor_id
Well, if you must have it all in one query, you could do a union:
SELECT distributor_id, COUNT() FROM ... UNION
SELECT COUNT() AS EXEC_COUNT FROM ... WHERE level = 'exec' UNION
SELECT COUNT(*) AS PERSONAL_COUNT FROM ... WHERE level = 'personal';
Or, if you can do after processing:
SELECT distributor_id, COUNT(*) FROM ... GROUP BY level;
You will get the count for each level and need to sum them all up to get the total.
I do something like this where I just give each table a string name to identify it in column A, and a count for column. Then I union them all so they stack. The result is pretty in my opinion - not sure how efficient it is compared to other options but it got me what I needed.
select 'table1', count (*) from table1
union select 'table2', count (*) from table2
union select 'table3', count (*) from table3
union select 'table4', count (*) from table4
union select 'table5', count (*) from table5
union select 'table6', count (*) from table6
union select 'table7', count (*) from table7;
Result:
-------------------
| String | Count |
-------------------
| table1 | 123 |
| table2 | 234 |
| table3 | 345 |
| table4 | 456 |
| table5 | 567 |
-------------------
Based on Taryn's response with an added nuance using OVER():
SELECT distributor_id,
COUNT(*) total,
SUM(case when level = 'exec' then 1 else 0 end) OVER() ExecCount,
SUM(case when level = 'personal' then 1 else 0 end) OVER () PersonalCount
FROM yourtable
GROUP BY distributor_id
Using OVER() with nothing in the () will give you the total count for the whole dataset.
I think this can also works for you select count(*) as anc,(select count(*) from Patient where sex='F')as patientF,(select count(*) from Patient where sex='M') as patientM from anc
and also you can select and count related tables like this select count(*) as anc,(select count(*) from Patient where Patient.Id=anc.PatientId)as patientF,(select count(*) from Patient where sex='M') as patientM from anc
In Oracle you'll do something like
SELECT
(SELECT COUNT(*) FROM schema.table1),
(SELECT COUNT(*) FROM schema.table2),
...
(SELECT COUNT(*) FROM schema.tableN)
FROM DUAL;
If your flavor of SQL supports it, you can use COUNT_IF() to count based on a condition.
SELECT
distributor_id,
COUNT(*) AS total_count,
COUNT_IF(level = 'exec') AS exec_count,
COUNT_IF(level = 'personal') AS personal_count
FROM table_name
GROUP BY distributor_id
The recently added PIVOT functionality can do exactly what you need:
SELECT *
FROM ( SELECT level from your_table )
PIVOT ( count(*) for level in ('exec', 'personal') )
I need to concat multiple row column values into one column. I know I can use GROUP_CONCAT for that. But it does not fit my needs. This is my query:
SELECT
GROUP_CONCAT(twv.value ORDER BY twv.id ASC SEPARATOR ';') as needed_values
FROM table_with_values twv
WHERE twv.valuetype_id IN (9,12,13,15,17,29)
GROUP BY twv.person_id
The problem is that when a row with for example valuetype_id = 13 is not found, this value will of course not be concatenated.
How can i accomplish that in the case a person_id does not have a value for valuetype_id = 13 that '-' will be inserted in that part?
Thanks
#Giles
I tried your idea, and later changed it a bit. Tested the query below and it gives me 5 rows instead of the expected 6 (because i'm left joining??).
SELECT vid
FROM (SELECT 9 vid UNION SELECT 12 UNION SELECT 13 UNION SELECT 15 UNION SELECT 17 UNION SELECT 29) vids
LEFT JOIN sollicitant_profiel sp1 ON (sp1.vraag_id = vids.vid)
WHERE sp1.sollicitant_id = 1
Whereas this one does work and gives 6 rows as expected:
SELECT vids.vid, vids2.vid
FROM (SELECT 9 vid UNION SELECT 12 UNION SELECT 13 UNION SELECT 15 UNION SELECT 17 UNION SELECT 29) vids
LEFT JOIN (SELECT 9 vid UNION SELECT 12 UNION SELECT 13 UNION SELECT 15 UNION SELECT 17) vids2 ON (vids.vid = vids2.vid)
Something like this should work:
SELECT
GROUP_CONCAT(COALESCE(twv.value,'-') ORDER BY twv.id ASC SEPARATOR ';') as needed_values
FROM table_with_values twv
RIGHT JOIN (SELECT 9 vid UNION SELECT 12 UNION SELECT 13 UNION SELECT 15 UNION SELECT 17 UNION SELECT 29) vids
ON vids.vid = twv.valuetype_id
GROUP BY twv.person_id
Not having your values I am unable to test it. The "vids" sub-select may be better as a temp table.
you can use IF_NULL , it returns second parameter '-' when GROUP_CONCAT IS NULL.
SELECT
IF_NULL(GROUP_CONCAT(twv.value ORDER BY twv.id ASC SEPARATOR ';'),'-') as needed_values
FROM table_with_values twv
LEFT JOIN (SELECT 9 vid UNION SELECT 12 UNION SELECT 13 UNION SELECT 15 UNION SELECT 17 UNION SELECT 29) vids
ON vids.vid = twv.valuetype_id
GROUP BY twv.person_id
I have the following details in MySQL as
user_id follow_user_id
1 2,3,3,3,3
5 1,2,3,3,3,3
6 1,2,3,3,3,3
i write the following code to get the unique code as follow:
SELECT LENGTH( follow_user_id ) - LENGTH( REPLACE( follow_user_id, ',', '' ) ) +1 AS no_of_follow FROM follow WHERE user_id =1;
But it provide the result:6
I need exactly unique rows: i.e:4
Apart from DB design questions you could use in PHP after fetching the row to $result:
count(array_unique(explode(",",$result["follow_user_id")));
$query="SELECT follow_user_id FROM follow WHERE user_id ='".$_POST['user_id']."' "; $query_run=mysql_query($query); $row= mysql_fetch_assoc($query_run);
$count= count(array_unique(explode(",",$row['follow_user_id'])));
$count;
This is better and faster ;)
count(array_flip(explode(",", $result["follow_user_id")));
Or doing it in SQL:-
SELECT COUNT(DISTINCT SUBSTRING_INDEX(SUBSTRING_INDEX(follow_user_id, ',', units.i + tens.i * 10), ',', -1) AS col1)
FROM sometable
CROSS JOIN (SELECT 0 i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9)units
CROSS JOIN (SELECT 0 i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9)tens
WHERE user_id = 1
(copes with up to 100 comma separated values).
But this would be so much easier with a properly normalised database design
for example:
my products best sort string is "'8207,17631,16717,18545,9062,17469,17246,17750"
this string is posted from php , I dont want to store them in datebase. I want to query datas from mysql and left join a temp table then sort by the temp table'sort.
how can I get this temp table from a string ?
my codes seems will be like that bellow:(wrong codes)
select
p.products_id
from
(
select '18207,17631,16717,18545,9062,17469,17246,17750' as products_id
) as p
order by p.sort
Your best approach could be - to use UNION for generating row set from string. This, however, will require joining your string in your application, like this:
$string = '18207,17631,16717,18545,9062,17469,17246,17750';
$id = 0;
$sql = join(' UNION ALL '.PHP_EOL, array_map(function($item) use (&$id)
{
return 'SELECT '.(++$id).' AS sort, "'.$item.'" AS products_id';
}, explode(',', $string)));
-end result will be like:
SELECT 1 AS sort, "18207" AS products_id UNION ALL
SELECT 2 AS sort, "17631" AS products_id UNION ALL
SELECT 3 AS sort, "16717" AS products_id UNION ALL
SELECT 4 AS sort, "18545" AS products_id UNION ALL
SELECT 5 AS sort, "9062" AS products_id UNION ALL
SELECT 6 AS sort, "17469" AS products_id UNION ALL
SELECT 7 AS sort, "17246" AS products_id UNION ALL
SELECT 8 AS sort, "17750" AS products_id
However, if you want to do that in SQL - that will not be easy, since MySQL doesn't supports sequences - and, therefore, you'll need to use some tricks to produce desired rows set. There's a way to generate N consecutive numbers with:
SELECT id+1
FROM
(SELECT
(two_1.id + two_2.id + two_4.id +
two_8.id + two_16.id) AS id
FROM
(SELECT 0 AS id UNION ALL SELECT 1 AS id) AS two_1
CROSS JOIN (SELECT 0 id UNION ALL SELECT 2 id) AS two_2
CROSS JOIN (SELECT 0 id UNION ALL SELECT 4 id) AS two_4
CROSS JOIN (SELECT 0 id UNION ALL SELECT 8 id) AS two_8
CROSS JOIN (SELECT 0 id UNION ALL SELECT 16 id) AS two_16
) AS init
LIMIT 10
-this will result in 10 numbers 1..10 (check this fiddle). Using this, you can get your end result:
SELECT
ELT(id+1, 18207,17631,16717,18545,9062,17469,17246,17750) AS products_id,
id+1 AS sort
FROM
(SELECT
(two_1.id + two_2.id + two_4.id +
two_8.id + two_16.id) AS id
FROM
(SELECT 0 AS id UNION ALL SELECT 1 AS id) AS two_1
CROSS JOIN (SELECT 0 id UNION ALL SELECT 2 id) AS two_2
CROSS JOIN (SELECT 0 id UNION ALL SELECT 4 id) AS two_4
CROSS JOIN (SELECT 0 id UNION ALL SELECT 8 id) AS two_8
CROSS JOIN (SELECT 0 id UNION ALL SELECT 16 id) AS two_16
) AS init
HAVING
products_id IS NOT NULL
-check this fiddle. However, this may be slow and I recommend you to use your application layer to build desired SQL.
something like this? use UNION to generate inline view. this can be generated by Client side.
SELECT *
FROM
(
SELECT '18207' AS products_id, 1 as sort
UNION
SELECT '17631' AS products_id, 2 as sort
UNION
SELECT '16717' AS products_id, 3 as sort
UNION
SELECT '18545' AS products_id, 4 as sort
UNION
SELECT '9062' AS products_id, 5 as sort
) x JOIN tbl x.products_id = tbl.products_id
ORDER BY sort
Totally 12 db tables(some tables repeated). I have to fetch SUM(values) from each table of particular date.I have used UNION query,But it returns the value of first table used in query.
Remaining table returned nothing.Can Anybody help me.Here my code.
$sel = mysql_query("
SELECT
SUM(collection_amount) AS cash_total
FROM
collection_entry
WHERE
date='$entered_date'
AND collection_type='DC'
UNION
SELECT
SUM(amt) AS cheque_redeposit_total
FROM
cheque_redeposit
WHERE
redeposited_on1
OR redeposited_on2='$entered_date'
UNION
SELECT
SUM(collection_amount) AS not_cleared_total
FROM
collection_entry
WHERE
cheque_status='not cleared'
AND date='$entered_date'
UNION
SELECT
SUM(collection_amt) AS route_collection_total
FROM
route_collection
WHERE
entered_date='$entered_date'
UNION
SELECT
SUM(amt) AS return_total
FROM
cheque_return
WHERE
return_date1 OR return_date2 OR return_date3='$entered_date'
UNION
SELECT
SUM(collection_amount) AS cheque_total
FROM
collection_entry
WHERE
collection_type='CC'
AND date='$entered_date'
UNION
SELECT
SUM(debit2) AS voucher_receipt_total
FROM
voucher_posting
WHERE
receipt_type='R'
AND date='$entered_date'
UNION
SELECT
SUM(credit2) AS voucher_payment_total
FROM
voucher_posting
WHERE
receipt_type='P'
AND date='$entered_date'
UNION
SELECT
SUM(amt) AS others_total
FROM
others_remittance
WHERE
entered_date='$entered_date'
UNION
SELECT
SUM(amt) AS short_total
FROM
short_remittance
WHERE
entered_date='$entered_date'
UNION
SELECT
SUM(amount) AS more_paid
FROM
difference
WHERE
entered_date='$entered_date'
and paid_type='more'
UNION
SELECT
SUM(amount) AS unpaid
FROM
difference
WHERE
entered_date='$entered_date'
and paid_type='unpaid'");
while($row=mysql_fetch_array($sel))
{
$cash_total=$row['cash_total'];
$cheque_redeposit_total=$row['cheque_redeposit_total'];
$not_cleared_total=$row['not_cleared_total'];
$route_collection_total=$row['route_collection_total'];
$return_total=$row['return_total'];
$cheque_total=$row['cheque_total'];
$voucher_receipt_total=$row['voucher_receipt_total'];
$voucher_payment_total=$row['voucher_payment_total'];
$others_total=$row['others_total'];
$short_total=$row['short_total'];
$more_paid=$row['more_paid'];
$unpaid=$row['unpaid'];
$net_total = (($cash_total + $route_collection_total) - $return_total);
}
UNION just appends rows to one another. So in your case you just get a list of your sums in a row-wise fashion.
[value for cash_total]
[value for cheque_redeposit_total]
[value for not_cleared_total]
...
If you really have to get all the data in one row, you can use something like this:
SELECT * FROM
(SELECT SUM(collection_amount) AS cash_total FROM collection_entry WHERE date='$entered_date' AND collection_type='DC') as t1,
(SELECT SUM(amt) AS cheque_redeposit_total FROM cheque_redeposit WHERE redeposited_on1 OR redeposited_on2='$entered_date') AS t2,
(SELECT SUM(collection_amount) AS not_cleared_total FROM collection_entry WHERE cheque_status='not cleared' AND date='$entered_date') AS t3,
(SELECT SUM(collection_amt) AS route_collection_total FROM route_collection WHERE entered_date='$entered_date') AS t4,
...