How to use Sum() function with condition? [closed] - sql

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

Related

How to get column values as a table column in sql [closed]

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 3 years ago.
Improve this question
This is my table defined in the database:
pi_value | Status
------------+-------------------
500.000 | Bank Submitted
500.0000 | Bank Submitted
1000.0000 | Maturity Received
4000.0000 | Bank Submitted
50.0000 | Maturity Received
I want the output to look like this:
Maturity Received | Bank Submitted |
------------------+----------------+
1050.0000 | 5000.0000 |
------------------+----------------+
use conditional aggregation
select sum(case when status='Bank Submitted' then pi_value else 0 end),
sum(case when status='Maturity Received' then pi_value else 0 end) from table
As you say in a comment that the status is not before-known, just select the mere data and have your app or website do the layout:
select status, sum(pi_value) as total
from mytable
group by status
order by status;
Whatever programming language you are using, it will be easy to simply loop through the result set and fill some grid with it.
Alternative:
If you want to get the pivoted data right away, you'll have to use dynamic SQL instead. This means you select the data needed to build the query first, then you build the query from it and run it. Here is how to get the statuses:
select distinct status from mytable order by status;
Then loop through these and construct a query like shown in Zaynul Abadin Tuhin's answer. Then run that query.

SQL QUERY SQL SSRS [closed]

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)

SQL select statement to Exclude a column from being sorted [closed]

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 7 years ago.
Improve this question
I am looking for a way to exclude a single column from being sorted using SQL select statement.
Lets say a table has 10 columns and when an ORDER BY is done on a specific column using select statement, all the 10 columns are sorted. Is it possible to exclude any specific column (say column 6) from being sorted? If so how.
**
Before
ID name
-----------
1 papaya
2 apple
3 strawberry
4 banana
Required
ID name
-----------
1 apple
2 banana
3 papaya
4 strawberry
Appreciate your help
This will generate the ids and they will be always shown in order but that won't be the actual id, you might need that as well
SELECT #a:=#a+1 id,name from tableName order by name

Oracle SQL : Union and Joins [closed]

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.

Comparing row based on contents to another tables rows in Access SQL

Hi I'm working on a project and for time constraint reasons I need to keep working in Access which may be the root of all my problems but maybe there's hope.
I have a database that includes a table ANSWERS filled with input for users "wants" there are multiple columns which each correspond to an answer to a different question asking if they, Don't Care, Want, or Need something.
EG: Answers:
Bacon | Ham | Sausage
________________________________
1 0 0 2
2 2 1 0
3 0 2 0
4 1 1 1
(0 = Don't Care, 1 = Want, 2 = Need)
I want to compare a row from table Answers to the Available table.
EG: Available:
Bacon | Ham | Sausage
________________________________
1 0 1 0
2 0 0 0
3 1 1 1
4 1 1 0
(0 = Unavailable, 1 = Available)
So I would want to compare row 1 from Answers to Available so because row 1 includes sausage=2 then I would want to receive row 3 from Available because sausage=1.
I'd be happy receiving the entire row, or the row ID and a "1" for the rows being a match.
Ultimately I'd need to do this for all each of the rows in Answers.
Any ideas are appreciated, I was thinking using Intersect might work but since that doesn't work in access. I've also considered joining the tables, I could also change data variables or formats if necessary.
Thanks very much
Edit: Don't Care was previously Don't Want. Changed for clarity.
Give this a try:
SELECT tblAnswers.UserID, IIf([tblAnswers].[bacon]>0 And [tblMenus].[Bacon]<>0,[MenuID],Null) AS BaconMenu, IIf([tblAnswers].[Ham]>0 And [tblMenus].[Ham]<>0,[MenuID],Null) AS HamMenu, IIf([tblAnswers].[Sausage]>0 And [tblMenus].[Sausage]<>0,[MenuID],Null) AS SausageMenu
FROM tblAnswers, tblMenus
WHERE (((IIf([tblAnswers].[bacon]>0 And [tblMenus].[Bacon]<>0,[MenuID],Null)) Is Not Null)) OR (((IIf([tblAnswers].[Ham]>0 And [tblMenus].[Ham]<>0,[MenuID],Null)) Is Not Null)) OR (((IIf([tblAnswers].[Sausage]>0 And [tblMenus].[Sausage]<>0,[MenuID],Null)) Is Not Null));
Just paste that into a SQL view make Query window (After changing the table and column names to match yours) You will obviously need to tweak it as reality needs, but it does what you asked for with the data provided.