View previous topic :: View next topic
|
Author |
Message |
kalidasvs
New User
Joined: 08 Feb 2018 Posts: 11 Location: US
|
|
|
|
I have a table as below:
Order#, item #, Total Order Amount
Order#, item #, Total Order Amount
Order#, item #, Total Order Amount
Order-1, Item-1, 500.00
Order-1, Item-3, 500.00
Order-1, Item-4, 500.00
Order-2, Item-2, 800.00
Order-2, Item-4, 800.00
Order-3, Item-4, 900.00
Order-3, Item-5, 900.00
In this table, there can be multiple rows for each Order number based on number of items on the order. However, each row has the Total order amount.
I need to find the sum of all orders. For each order only one row should be considered. Otherwise, the amount gets added multiple times.
I wrote query as below:
SELECT SUM(ORD_AMT)
FROM ORDER_TAB A
ITEM_NUM = (SELECT MIN(ITEM_NUM) FROM ORDER_TAB
WHERE ORDER_NUM = A.ORDER_NUM)
Expected result = 2200.00
I wrote this query assuming that the subquery returns minimum item number which causes only one row per order is considered in finding total amount. However, when I submitted trough SPUFI, the query is running for very long time and I had to cancel the session. Please help me resolve this. Unfortunately, I coded SQL many years ago so I lost touch. |
|
Back to top |
|
|
dneufarth
Active User
Joined: 27 Apr 2005 Posts: 420 Location: Inside the SPEW (Southwest Ohio, USA)
|
|
Back to top |
|
|
Rohit Umarjikar
Global Moderator
Joined: 21 Sep 2010 Posts: 3077 Location: NYC,USA
|
|
|
|
Its so very basic.
Code: |
select sum(distinct(Order Amount)) from table group by order# |
*provided the amount per order always duplicate for all the items as per the ex you provided. |
|
Back to top |
|
|
kalidasvs
New User
Joined: 08 Feb 2018 Posts: 11 Location: US
|
|
|
|
Rohit Umarjikar wrote: |
Its so very basic.
Code: |
select sum(distinct(Order Amount)) from table group by order# |
*provided the amount per order always duplicate for all the items as per the ex you provided. |
This does not work. I need the total of order amounts from each of the distinct orders. Your query only considers unique amounts instead of unique order numbers. If two different orders have same order amount, then result will be wrong. |
|
Back to top |
|
|
Rohit Umarjikar
Global Moderator
Joined: 21 Sep 2010 Posts: 3077 Location: NYC,USA
|
|
|
|
Do you know what is Group by?
please clear up the concepts. |
|
Back to top |
|
|
kalidasvs
New User
Joined: 08 Feb 2018 Posts: 11 Location: US
|
|
|
|
Yes. I use Group by.
Rohit Umarjikar wrote: |
Do you know what is Group by?
please clear up the concepts. |
|
|
Back to top |
|
|
Rohit Umarjikar
Global Moderator
Joined: 21 Sep 2010 Posts: 3077 Location: NYC,USA
|
|
|
|
You all need is just another select on top if it to sum the total of the above query. to get 2200 |
|
Back to top |
|
|
|