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.
Related
I have an existing table (link #1) that I am trying to write a query for so that the query reformats the data as seen in the second link. Basically it is a table listing the completed email types for a group of users. The "Completed Type" is a single column with multiple values. I am trying to parse out the individual values (3 of them) from the "Completed Type" into their own column with a total count. I also would like to add a seperate column called "Completed" which is simply a sum of "Closed without response" and "Replied" for that particular user for that particular month.
I plan on then creating a pivot in Excel that will read off of the new query with the reformated data. For the life of me, I can't figure out how to write this in SQL. I tried creating individual queries to total the different "Completed" types and then tried to union them, but it is not working.
Existing table
Future Query Output
Any advice or guidance you can provide in writing a SQL query in Access that will produce image # 2 would be GREATLY appreciated! Thank you in advance!
You can use case when and sum, for example:
select month,
id,
sum(case when completed_type = "completed" then 1 else 0 end) as completed
from table
group by month, id
Use a crosstab query:
TRANSFORM
Sum([Case Count]) AS [SumOfCase Count]
SELECT
[Month],
ID,
[Adjusted Name],
Mgr,
Sup,
Region,
Region2,
Sum(Abs([Completed Type] Not Like "Closed*")) AS Completed
FROM
Cases
GROUP BY
[Month],
ID,
[Adjusted Name],
Mgr,
Sup,
Region,
Region2
ORDER BY
ID,
[Month] DESC
PIVOT
[Completed Type] In ("Replied","Sent","Closed without response");
Output:
---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 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.
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
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 ....