How to merge two or more queries with different where conditions? I have to reuse the code which is being used in 1st where code - sql

---below query gives all the customers from fact irrespective of condition
SELECT count( dbo.Fact_Promotion.customerid) as Mailquantity
FROM dbo.Fact_Promotion
INNER JOIN dbo.Dim_Promotion
ON dbo.Fact_Promotion.PromotionID = dbo.Dim_Promotion.PromotionID
---below query gives customers with where condition
SELECT count(distinct fact_loan.customerid) as [New loans] ,avg(Fact_Loan.Financeamount) as [Avg New Loan Amount]
FROM dbo.Fact_Promotion
where <condition>
AND dbo.Fact_Loan.LoanTypeID = 6
AND dbo.Fact_Loan.AccountStatusID = 1
----below query gives customers with different where condition
SELECT count(distinct fact_loan.customerid) as [Total loans],avg(Fact_Loan.Financeamount) as [Avg Total Loan Amount]
FROM dbo.Fact_Promotion
where <condition>
AND dbo.Fact_Loan.AccountStatusID = 1

I'm not sure from your question what you are trying to achieve.
The WHERE clause in the second query appears to deliver a subset of the data from the WHERE clause in the third query. Both WHERE statements look identical with the exception that the second query (New loans) includes an extra condition that the LoanTypeId (presumably the financial product they have taken) is 6. I guess this is the latest loan product or campaign.
Without knowing what you're trying to do it's difficult to give you an answer but if you want to show total number of customers by LoanTypeId you could aggregate a count by adding the LoanTypeId column to the SELECT statement and adding a GROUP BY dbo.Fact_Loan.LoanTypeId to the end of the statement.
This may not be a straight forward as that as you're doing some other stuff in your SELECT (such as the DISTINCT and the AVG) but without knowing what your end goal is, it's difficult to fully answer your question.

Related

MS Access - Summing up a field to be used in another query is "duplicating" data

I am trying to sum up one field and use it in another query, but when I use the Totals button and then call that sum from the other query it considers that field as multiple instances but with the sum value in each one. How can I sum two fields in two different queries and then use those sums in another query? Note - I only separated them into 3 queries because I felt it would help me avoid "is not part of an aggregate function" errors.
Example Data
Inventory Query: This query groups by item and sums the qty_on_hand field
Item SumOfqty_on_hand
A 300
Job Material query: This query groups on the job's materials and sums up the qty_req field (quantity required to complete the job)
Item SumOfqty_req
A 500
When I make a third query to do the calculation [SumOfqty_req]-[SumOfqty_on_hand] the query does the calculation but for each record in the Job Material query.
Job Material Query
SELECT dbo_jobmatl.item,
IIf(([qty_released]-[qty_complete])<0,0,([qty_released]-[qty_complete]))*[matl_qty] AS qty_req
FROM new_BENInventory
INNER JOIN (dbo_jobmatl
INNER JOIN new_BENJobs
ON (new_BENJobs.suffix = dbo_jobmatl.suffix)
AND (dbo_jobmatl.job = new_BENJobs.job)
) ON new_BENInventory.item = dbo_jobmatl.item
GROUP BY dbo_jobmatl.item,
IIf(([qty_released]-[qty_complete])<0,0,([qty_released]-[qty_complete]))*[matl_qty];
Inventory Query
SELECT dbo_ISW_LPItem.item,
Sum(dbo_ISW_LPItem.qty_on_hand) AS SumOfqty_on_hand,
dbo_ISW_LP.whse,
dbo_ISW_LPItem.hold_flag
FROM (dbo_ISW_LP INNER JOIN dbo_ISW_LPItem
ON dbo_ISW_LP.lp_num = dbo_ISW_LPItem.lp_num)
INNER JOIN dbo_ISW_LPLot
ON (dbo_ISW_LPItem.lp_num = dbo_ISW_LPLot.lp_num)
AND (dbo_ISW_LPItem.item = dbo_ISW_LPLot.item)
AND (dbo_ISW_LPItem.qty_on_hand = dbo_ISW_LPLot.qty_on_hand)
GROUP BY dbo_ISW_LPItem.item,
dbo_ISW_LP.whse,
dbo_ISW_LPItem.hold_flag
HAVING (((Sum(dbo_ISW_LPItem.qty_on_hand))>0)
AND ((dbo_ISW_LP.whse) Like "BEN")
AND ((dbo_ISW_LPItem.hold_flag) Like 0));
Third Query
SELECT new_BENJobItems.item,
[qty_req]-[SumOfqty_on_hand] AS [Transfer QTY]
FROM new_BENInventory
INNER JOIN new_BENJobItems
ON new_BENInventory.item = new_BENJobItems.item;
Please note that anything that starts with dbo_ is a prefix for a table that sources the original data.
If any more clarification is needed I would be more than happy to provide it.
Looks like you need a GROUP BY new_BENJobItems.item on your final query along with a SUM() on the quantity. Or to remove the IIf(([qty_released]-[qty_complete])<0,0,([qty_released]-[qty_complete]))*[matl_qty] from your Job Material query. Or both. As written, the Job Material Query is going to return a record for every different key value in the joined input tables that has a distinct quantity, which doesn't seem like the granularity you want for that.

SQL postgres query

I have a query that I'm trying to perform below. However, being unable to test my query, I am unsure of my result.
The donors who have donated at least $10,000 since January 1, 2010 (donor ID, name, total
gifts).
SELECT donor_id,
donor_name,
SUM (amount) AS total_gifts_since_2010
FROM donor
JOIN gift
USING (donor_id)
JOIN gift_fund_allocation
USING (gift_id)
JOIN fund
USING (fund_id)
WHERE gift_date >= ‘01/01/2010'
GROUP BY (donor_id, donor_name)
HAVING total_gifts_since_2010 >= 10000;
Either one of two things will happen:
What I want it to do, which is only adds amounts after 2010.
Not what I want it to do, which is add all the amounts, but only
select/display the ones after 2010.
So my question would be something like this: Does the entire query happen instruction-by-instruction, or does the WHERE clause have an immediate effect on the query?
1) WHERE should precede GROUP BY (in the statement)
2) The sequence is following: JOIN - WHERE - GROUP BY - SELECT list

Newb help in designing query to subtract results of two queries in same table

I have seen other questions like this one but feel mine is a bit different, or didn't quite understand the SQL in the other questions...so my apologies if this one is redundant or very easy..
Anyway, I have an accounting transaction DB that stores every transaction posting within our financial system on one line. What I am trying to do is net the sum of the debits and the credits for each GL account.
Here are the two basic queries I am executing to get the results that I would like to net.
Query 1 gives me the sum of all debit transactions posting to each gl account:
Select gl_debit, sum (amt) from FISC_YEAR2014 where fund = 'XXX'
group by gl_debit
Query 2 gives me the sum of all credit transactions posting to each gl account:
select gl_credit, sum (amt) from FISC_YEAR2014 where fund = 'XXX'
group by gl_credt
Now I would to subtract the credit amounts from the debit amounts to get net totals for each gl account. Make sense?
Thanks.
There are two ways to do this depending our your table definition. I think your situation is the first.
This is the normal way assuming credits and debits are in separate columns:
SELECT sum(gl_debit)-sum(gl_credit) as net_debit
FROM FISC_YEAR2014
WHERE fund = 'XXX'
This is the other way assuming direction is indicated by a separate column:
SELECT SUM(IF(is_debit=1,amount,-1*amount)) as net_debit
FROM FISC_YEAR2014
WHERE fund = 'XXX'
See also:
MySQL 'IF' in 'SELECT' statement
Can't calculate totals in general ledger report
What's a good way to store a financial ledger?
I believe this is what you need:
select
gl_account,
sum(amt)
from
(
select gl_debit gl_account,
sum(-amt) amt
from fisc_year2014
where fund = 'XXX'
group by gl_debit
union all
select gl_credit,
sum(amt)
from fisc_year2014
where fund = 'XXX'
group by gl_credit
)
group by
gl_account
There are two SELECTs: one to get the (negative) debits and another to get the credits. They are UNIONed to create a two-column result. The outer SELECT then aggregates the total sum by the gl_account code. If there is a mismatch (a gl_debit without a gl_credit, or vice-versa), then its amount would still be displayed.
SQLFiddle here (I added another row to show the effect of mismatched IDs)
To do this you should SUM the debits and credits separately in subqueries, then join those subqueries on gl_credit = gl_debit.
SELECT COALESCE(gl_credit, gl_debit) AS Id
,COALESCE(d.amt,0)-COALESCE(c.amt,0) AS Net
FROM (
SELECT gl_debit, SUM(amt) AS amt
FROM FISC_YEAR2014
GROUP BY gl_debit
) d
FULL OUTER JOIN (
SELECT gl_credit, SUM(amt) AS amt
FROM FISC_YEAR2014
GROUP BY gl_credit
) c ON d.gl_debit = c.gl_credit
ORDER BY COALESCE(gl_credit, gl_debit)
SQLFiddle
Outputs:
ID Net
-----------
101 -475
201 225
301 500
501 -250
If I were you rather than using a FULL OUTER JOIN, I'd select the ids from the accounts table or wherever you store them, then LEFT JOIN both of the subqueries to it, you haven't shown any other tables though so I can only speculate.

Crystal Report: remove duplicates

I am working with Crystal Report to pull Charges and the Transactions associated with those Charges. One Charge might have many Transactions attached to it, and one Transaction might cover many Charges. As I put this report together, the Transactions would repeat themselves if there were many Charges in that revenue code group. And if there are many Transactions for one Charge, the Charge would duplicate itself. I also have to do subtotal and grandtotal for these Charges and Transactions, so if there are duplicates in data, the totals would also incr
How do I remove those duplicates?
Below is the SQL query for this report:
SELECT DISTINCT
A123Test_ChargeOnly."enc_nbr",
A123Test_ChargeOnly."revenue_code_id",A123Test_ChargeOnly."Charge",
A123Test_TransOnly."Tran_Description", A123Test_TransOnly."tran_amt"
FROM
{ oj "NGProd"."dbo"."123Test_ChargeOnly" A123Test_ChargeOnly
INNER JOIN "NGProd"."dbo"."123Test_TransOnly" A123Test_TransOnly ON
A123Test_ChargeOnly."enc_nbr" = A123Test_TransOnly."enc_nbr"}
ORDER BY
A123Test_ChargeOnly."enc_nbr" ASC,
A123Test_ChargeOnly."revenue_code_id" ASC
Rather than joining the two tables, I suggest UNIONing them - something like:
SELECT 'Charge' record_type, enc_nbr, revenue_code_id, Charge, '' Tran_Description, 0 tran_amt
FROM "NGProd"."dbo"."123Test_ChargeOnly"
UNION ALL
SELECT 'Transaction' record_type, enc_nbr, '' revenue_code_id, 0 Charge, Tran_Description, tran_amt
FROM "NGProd"."dbo"."123Test_TransOnly"
ORDER BY 2, 1, 3
As far as I remember, there is a specific 'suppress if duplicate' option in the 'sections' expert of Crystal Reports ....

Microsoft Access 2003 - creating a separate field that totals 5 other fields from the table

This is what i have so far in the SQL code........
SELECT DISTINCTROW [OEE/A Query].Press,
Sum([OEE/A Query].[SumOfLabor Hours]) AS [Sum Of SumOfLabor Hours],
Sum([OEE/A Query].[SumOfGood Pieces]) AS [Sum Of SumOfGood Pieces],
Sum([OEE/A Query].[Scrap Pieces]) AS [SumOfScrap Pieces],
Sum([OEE/A Query].[SumOfMachine Hours]) AS [SumOfSumOfMachine Hours],
Sum([OEE/A Query].[Total Parts Hours Earned]) AS [SumOfTotal Parts Hours Earned],
Sum([OEE/A Query].[Standard Pcs Expected]) AS [Stand Pcs Expected]
FROM [OEE/A Query]
GROUP BY [OEE/A Query].Press;
How do i add to this code another field that totals 5 separate other fields?
Here's what i think it might look like but I'm not sure.....
SELECT Sum(Sort+Straighten+Shine+Standardize+Sustain)
SUM(Sort),
SUM(Straighten),
SUM(Shine),
SUM(Standardize),
SUM(Sustain),
FROM [Shift Report Table];
it depends on what you are really asking. I am not sure if your second query is just another example, or, if it is in fact a different data source to be added into your first query.
If you want to add another column to your first query example based on the columns that already exist in your query then yes, simply add them together, as per CK says.
e.g.
select sum(column1) + sum(column2) as sum_c1_c2
or
select sum(column1 + column2) as sum_c1_c2
when doing aggregate functions I have an old habit of handling NULL values to make sure I am getting the results I think I should be getting. e.g.
select sum(nz(column1,0) + nz(column2,0)) as sum_c1_c2
Now if you are asking how to add a new column from a different data source, then you can either join to that other datasource, or, if returning just a single value, can use an inline select.
Also, a word of warning about distinctrow - I am not sure you want to use that in your query. You are doing a group by, so only the unique values for [press] will be selected with the aggregated columns as per your SUM() function. It is really hand for things like determining if (by way of example) a Product has been ordered e.g.
select DISTINCTROW productname
from products
inner join orders on orders.productid = products.productid
will return just 1 row so there is no chance for any aggregation in the above case.
But you might want to clarify your requirement a bit more. CK might have already given the answer, or, we might need to include a different datasource (such as your second query).
Yes, that is correct. You can add fields within the sum function, to sum the sum of the fields.