I have Two Tables of related data.
Table 1 - All Trading history by broker
Table 2 - All Trade Breaks (trades which had errors / differences / issues)
I created a Query to Total the number of trades by Broker from Table 1
I created a Query to Total the number of "Breaks" by Broker from Table 2
I then created a Query to combine the two previous Queries and produce some statistics
Example:
Broker Total Trades Total Breaks Break %
Goldman 10 4 40%
Morgan 10 2 20%
Rather than create 3 queries - is there a way to create 1 query which achieves the same result? I want to perform more detailed analysis / reports without inundating the database with tons of individual queries. SQL Code Below
First Query:
SELECT DISTINCTROW [All Breaks].Broker, Sum([All Breaks].TradeCount) AS
[Sum Of TradeCount]
FROM [All Breaks]
GROUP BY [All Breaks].Broker;
Second Query:
SELECT DISTINCTROW [All Trades].Broker, Sum([All Trades].TradeCount) AS
SumOfTradeCount
FROM [All Trades]
GROUP BY [All Trades].Broker;
end Result: Combining
SELECT [Broker List].Broker, [All Breaks Query].[Sum Of TradeCount], [All
Trades Query].SumOfTradeCount, [Sum Of TradeCount]/[SumOfTradeCount] AS
Percentage
FROM ([Broker List] INNER JOIN [All Breaks Query] ON [Broker List].Broker
= [All Breaks Query].Broker) INNER JOIN [All Trades Query] ON [Broker
List].Broker = [All Trades Query].Broker;
Thanks Very Much!
In query design, there is a way to switch to SQL View, where you can freely write sql.
select one, two
from
(select one, joinfield from table1) as first
Inner join (select two, joinfield from table2) as second
ON first.joinfield = second.joinfield.
Also, see Combining two MS Access queries
Related
---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.
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.
I may just be tired, but I can't seem to figure out what is happening. I have two queries. Query 1 has 10 fields. Query 2 has 5 fields. Fields 1 through 3 are the same in both queries. I am trying to write a select query and simple add field 5 from Query2 to Query1 so my result should be Query1 with an additional field (Query2.field5).
I join the first 3 fields from both queries and choose select all records in query1 and only those in query2 that match. I don't know sql, so I use query designer. I expect to get the same number of records that I have from query 1 but instead I have 3 times or more. Can someone tell me what I am doing wrong. I even tried reversing the joins but still seem to get the same extra records.
Thanks in advance.
Here is the query:
The fields that are in common are DivisionName, SupplierID = VendorID and CommodityName.
SELECT [Part Revenue Exposed Query P1].DivisionName,
[Part Revenue Exposed Query P1].CommodityName,
[Part Revenue Exposed Query P1].SupplierName,
[Part Revenue Exposed Query P1].PartNumber,
[Part Revenue Exposed Query P1].PartDescription,
[Part Revenue Exposed Query P1].BUCode,
[Part Revenue Exposed Query P1].ProductLine,
[Vendor Risk Score Query].VendorScore
FROM [Part Revenue Exposed Query P1] LEFT JOIN [Vendor Risk Score Query]
ON ([Part Revenue Exposed Query P1].DivisionName = [Vendor Risk Score Query].DivisionName)
AND ([Part Revenue Exposed Query P1].SupplierID = [Vendor Risk Score Query].VendorID)
AND ([Part Revenue Exposed Query P1].CommodityName = [Vendor Risk Score Query].CommodityName);
This is most probably because there are multiple records in [Vendor Risk Score Query] matching the condition in [Part Revenue Exposed Query P1]. i.e. if corresponding to one record of [Part Revenue Exposed Query P1] with values:
DivisionName ='TestDiv', SupplierID = 1, CommodityName = 'TestCommodity'
there can be multiple records in [Vendor Risk Score Query] with values
DivisionName ='TestDiv', SupplierID = 1, CommodityName = 'TestCommodity'
then it will return more records than the number of records in [Part Revenue Exposed Query P1]
Check you join condition.
AND ([Part Revenue Exposed Query P1].SupplierID = [Vendor Risk Score Query].VendorID)
Is supplier to vendor correct?
You said the first three fields are the same. But it only shows two the same.
I am trying to display total of each stock with their description in a report. I have got 2 queries but do not know how to combine them. First query
SELECT
stock_partno, SUM(stock_qty) AS TotalStock
FROM
stock
GROUP BY
stock_partno;
Second query
SELECT DISTINCT
Stock.stock_PartNo, parts.parts_Desc
FROM
parts
INNER JOIN
stock
ON
parts.Parts_partno = Stock.stock_PartNo;
How do I combine both these queries so that they can display a report with total stock of each Part with their description?
To be able to select the parts_Desc column, add it to the GROUP BY clause. That will maintain the same grouping as in the first query (because each part number has just one description).
SELECT
SUM(stock.stock_qty) AS TotalStock,
Stock.stock_PartNo, parts.parts_Desc
FROM
parts
INNER JOIN
stock
ON
parts.Parts_partno = Stock.stock_PartNo;
GROUP BY
Stock.stock_partno, parts.parts_Desc;
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 ....