简体   繁体   中英

Get only the code and total number Oracle SQL

I have 2 tables below.I want to join them

Table1
--------------
T1_id | desc
--------------
1     | test 1
2     | test 2

table2 (detail)
---------------
T2_id  | Price
----------------
1      | 100000
1      | 0
1      | 0
2      | 300000
2      | 0
2      | 0
2      | 0

i want the results for this

--------------
code  | total
--------------
1     | 100000
2     | 300000

this query

select a.T1_id as Code,
b.price as Total
from Table1 a
inner join table2 b on b.T2_id = a.T1_id group by a.T1_id,b.price;

Use below query instead to get the total price

select a.T1_id as Code,
SUM(b.price) as Total
from Table1 a
inner join table2 b on b.T2_id = a.T1_id group by a.T1_id;

Sample output:

在此处输入图像描述

在此处输入图像描述

Referring to the sample

To exclude 0 values:

SELECT T1_ID AS CODE, PRICE AS PRICE FROM TABLE1 JOIN TABLE2 ON T1_ID=T2_ID
WHERE PRICE<>0

sum of same id:

SELECT T1_ID AS CODE, SUM(PRICE) AS PRICE FROM TABLE1 JOIN TABLE2 ON T1_ID=T2_ID
GROUP BY T1_ID

I fail to see where Table 1 comes into play at all. Presumably the t2_id is a FK back to t1_id. You aren't presenting the column DESC at all, so why are you bothering to join on table_1?

So what's wrong with simply

select t2_id CODE,
       sum(price) TOTAL
from table2
group by t2_id
order by t2_id
;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM