Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I am fairly new to sql. my question is how do I group by a field and then determine the difference between values in a column. for example.
claim# amount
1. c3101 50000
2. c3101 19000
3. c1307 30000
4. c1307 14000
5. c3104 75000
6. c3104 0
7. c1313 5000
8. c1313 10000
expected results
1. c3101 -31000
2. c1307 -26000
3. c1313 5000
i need to find the diffence between amounts relative to a claim number. so for c3101 i started at 50000 and went to 19000 so the transaction to get to 19000 would be -31000. c3104 would be ignored
You can use group by and sum to find the total values for a specific claim.
Finding the difference cannot be done unless you specify which claim amount was the first (unless you use the insertion/default order).
If we know which is first we could subtract with the other amount (or amount(s)).
If there are only two entries for each claim you can get the absolute different between the first() and last() entries.
select claim, abs(last(amount) - first(amount)) from claims group by claim;
You can also get the non-absolute difference, based on insertion order:
select claim, (last(amount) - first(amount)) from claims group by claim;
Update
As first() and last() are not supported in many DBs, below are alternatives:
MySQL
select distinct claim,
(select amount from claims c1 where c1.claim = c2.claim limit 1,1) -
(select amount from claims c1 where c1.claim = c2.claim limit 0,1) as "Difference"
from claims c2;
SQLFiddle: http://sqlfiddle.com/#!2/2e62a0/15
MS SQL
For MS SQL, as it is quite more difficult to get the bottom X records from a set, I make use of the average() function:
SELECT claim, ((avg(amount)*2) -
(SELECT top 1 amount
FROM claims c2
WHERE c2.claim = c.claim))-
(SELECT top 1 amount
FROM claims c2
WHERE c2.claim = c.claim)
FROM claims c
GROUP BY claim;
which is further simplified to:
SELECT claim,
2* ( avg(amount) -
(SELECT top 1 amount
FROM claims c2
WHERE c2.claim = c.claim))
FROM claims c
GROUP BY claim;
SQL Fiddle: http://sqlfiddle.com/#!3/2e62a/28
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I know how to do running sum but can't figure out how to do running subtract.
Example: we have single column of data and a new column will be formed for running subtraction.
Value
------
10
1
3
4
Output needs to be:
10
9
6
2
I need both these columns next to each other
Any suggestion please.
Your question only makes sense if you have a column that specifies the ordering. In that case:
select (case when row_number() over (order by <ordercol>) = 1
then col
else 2 * first_value(col) over (<ordercol>) - sum(col) over (order by <ordercol>)
end) as output
from t;
That is, return the column value on the first row. Otherwise, the math is a little tricky. But you want the first value minus the sum of the rest of the column. Arithmetically, this is the same as twice the first value minus the cumulative sum.
EDIT:
As Shawn points out, this can be simplified to:
select 2 * first_value(col) over (<ordercol>) - sum(col) over (order by <ordercol>) as output
from t;
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I have say 5000 records in a table with 20 unique ClientId's. How can I select 100 records in which all 20 unique clientId's are covered.
In SQL Server
Edit: Also how can I have a running total column in the same query
For ex there are 5 unique names
Id. Name. Amt. total
5. Abc. 10. 10
3. Def. 20. 30
6. Xxx. 5. 35
2. You. 10. 45
1. Fed. 20. 65
5. Abc. 5. 70
3. Def. 12. 82
.................
One method uses window functions. In standard SQL:
select t.*
from t
order by row_number() over (partition by clientid order by clientid)
fetch first 100 rows only;
In SQL Server, you would use top (100) if fetch is not available.
The row_number() will assign a value of "1" to one of the rows for each client. These will appear first. So, if there are 20 clients, then returning 20 rows will have one row per client. With 100 rows, you will have 5 rows per client -- unless some of the clients have fewer than 5 rows.
say you have a table with 5000 records
RecordId,ClientId,.......
Select top 100 * from table where (Select count(*) from table t where t.RecordId = Table.RecordId) = 20
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
Hi can anyone help me with sum up first two rows in table and then rest would be same. example is
ID SUM
12 60
0 20
1 30
2 50
3 60
I am expecting
ID SUM
0 80
1 30
2 50
3 60
I am doing this from memory - so if this doesnt work let me know and we can do it another way looking at the row number;
Assuming you have a unique ID to sort it by as you suggested, you could do something like this;
you may want to change the order to be desc if that's how you classify your 'top 2'
SELECT TOP 2 ID,
SUM(VALUE)
FROM [Table]
GROUP BY ID
ORDER BY ID
UNION
SELECT ID,
VALUE
FROM [Table]
WHERE ID NOT IN (SELECT TOP 2 ID
FROM [Table] ORDER BY ID)
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I have an Access database. There is a table named cost with bottom value:
reson Cost Type
------------ ------ ------
A1 2500 1
A1 6500 1
A2 95000 2
A3 2500 1
A1 6500 1
A4 50000 2
Now I want a query that calculate sum of all cost filed where type = 2 and sum of cost filed where type = 1 and substract the first value from the second value.
For example, the above pic calculate final result:
Sum of Type 2 = 145000
Sum of Type 1 = 18000
-------------------------
Final Result = 127000
My Sql Code
select iif(type = 2, sum(cost), -sum(cost)) As col1 from cost group by type
First off, I'm sorry you have to deal with such obnoxious hostility when asking your question here. You asked your question perfectly fine, laying out your table structure, and your desired result. It's understandable that you are new to queries and need help creating them. Not every answer requires code, and not every person knows where to start.
Here is your answer:
Step 1
Make sure you have your table created with the data you provided
Step 2
Create a new query named qySumType1. Build it like this, so it sums everything of type=1. make sure to click the totals button.
Step 3
Create another query, name this one qySumType2. This query should sum everything of type=2.
Step 4
Now create another query called "Final". Add both of your previous queries to it. Now create an expression in the last column to calculate the difference between the 2 numbers. Just like this.
And there you have it. Now just run the Final query anytime you want to get the difference.
Hope this helps! I can't tell you how many times I've started learning something new and relied on a community to help me get started. Always just try your best and wait for a decent answer to your question. Good luck!
Change T1 to the name of your table.
SELECT Sum(T.Type1) AS Type1, Sum(T.Type2) AS Type2, Sum(T.Type2) - Sum(T.Type1) AS DIFF
FROM
(
SELECT Sum(T1.Cost) AS Type1, 0 AS Type2
FROM T1
WHERE (((T1.Type)=1))
UNION
SELECT 0 AS Type1, Sum(T1.Cost) AS Type2
FROM T1
WHERE (((T1.Type)=2))
) AS T;
Type1 | Type2 | DIFF
18000 | 145000 | 127000
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I have a table ACCPLAN(PRIMARY KEY : ACCOUNT_ID)
ACCOUNT_ID PLAN_TYPE OTHER_STUFF
ACC1 PLAN_TYPE_ONE ....
ACC2 PLAN_TYPE_TWO ....
ACC3 PLAN_TYPE_ONE ....
ACC4 PLAN_TYPE_TWO ...
I have one more table ACCTRANSACTION (PRIMARY KEY -> (ACCOUNT_ID,TRANSACTION_ID)
ACCOUNT_ID TRANSACTION_ID TRANSACTION_AMOUNT TXN_TYPE
ACC1 1 100 TXN_TYPE_1
ACC1 2 300 TXN_TYPE_2
ACC2 1 400 TXN_TYPE_2
ACC3 1 400 TXN_TYPE_3
There are 5 fixed plan_types and 20 fixed txn_types.Only few transactions types are
possible for each plan_type.(For eg : TXN_TYPE_1 and TXN_TYPE_2 are possible for
PLAN_TYPE_ONE and TXN_TYPE_2 and TXN_TYPE_3 are possible for PLAN_TYPE_TWO)
I am trying to retrieve the transaction information from ACCTRANSACTION and other
details from ACCPLAN
This can be done in 2 ways
APPROACH 1
Retrieve for each plan_type and do an union
select ap.account_id,ap.other_stuff,at.transaction_amount
from accplan ap, acctransaction at
where ap.account_id = at.account_id
and ap.plan_type = PLAN_TYPE_ONE
and at.txn_type in (TXN_TYPE_1,TXN_TYPE_2);
union
select ap.account_id,ap.other_stuff,at.transaction_amount
from accplan ap, acctransaction at
where ap.account_id = at.account_id
and ap.plan_type = PLAN_TYPE_TWO
and at.txn_type in (TXN_TYPE_2,TXN_TYPE_3);
union
...
APPROACH 2
Retrieve using one query for all plan_types
select ap.account_id,ap.other_stuff,at.transaction_amount
from accplan ap, acctransaction at
where ap.account_id = at.account_id
and
((ap.plan_type = PLAN_TYPE_ONE and at.txn_type in (TXN_TYPE_1,TXN_TYPE_2))
or
(ap.plan_type = PLAN_TYPE_TWO and at.txn_type in (TXN_TYPE_2,TXN_TYPE_3));
which approach is better considering both tables have huge data?. Please suggest.
Use joins. Unions require sorting the whole result and it is an expensive operation for your database.
Furthermore. It is better to read the table one time and do some complex checks with each record than reading it several times just to make smaller checks.
Disclaimer: I can imagine some very strange corner cases where the first query runs faster if the database query planner decides that the big condition is not selective enough and does not uses an index and each of the smaller one does use it. The bigger the number of rows the more I would use the second option.