SQL/Microsoft Access Query Problems - sql

CNum DNum RNum Quant Price
C100 D1 R10 2 8.99
C100 D1 R40 7 9.99
C200 D3 R10 4 16.99
C200 D3 R20 2 15.99
C200 D3 R30 2 17.99
C200 D3 R40 5 19.99
C200 D3 R50 6 18.99
C200 D3 R60 4 19.99
C200 D3 R70 8 15.99
C200 D5 R20 1 8.99
C300 D3 R10 2 16.99
C300 D4 R20 5 22.99
C400 D6 R30 3 4.99
C400 D6 R70 3 2.99
C500 D1 R40 1 9.99
C500 D2 R20 2 23.99
C500 D2 R40 1 24.99
C500 D3 R40 2 19.99
C500 D4 R40 8 23.99
C500 D5 R40 4 8.99
C500 D5 R50 5 8.99
C500 D5 R70 1 9.99
C500 D6 R20 2 1.99
C500 D6 R40 5 3.99
The table above is name Orders. The Query I'm trying to solve is stated as "For each dish ordered from a restaurant, get the dish number(DNum), the restaurant number(RNum), and the total quantity (for that dish ordered from that restaurant)." I can get the two numbers to populate, but am totally unsure of how to add up the quantities, anything I've tried just adds up the Quantities in total. Any ideas?
Here is one of the queries I tried. This actually returned an error:"Your query does not include the specified expression 'DNum' as part of an aggregate function.'
SELECT Ord1.DNum, Ord2.DNum, SUM(Ord1.Quant + Ord2.Quant) AS TotQuant
FROM Orders AS Ord1, Orders AS Ord2
WHERE (Ord1.RNum = Ord2.RNum)
another thats not working
SELECT Order1.DNum, Order2.DNum, TotQuant
FROM (SELECT SUM(Order1.Quant + Order2.Quant) AS TotQuant
FROM Orders AS Order1, Orders AS Order2
WHERE (Order1.RNum = Order2.RNum)
AND (Order1.DNum = Order2.DNum))
and one more
SELECT DISTINCT Ord1.DNum, SUM(Ord1.Quant + Ord2.Quant) AS TotQuant
FROM Orders AS Ord1, Orders AS Ord2
WHERE (Ord1.RNum = Ord2.RNum)
AND (Ord1.DNum = Ord2.DNum)

If my guess as to what you are trying to do is correct something like this should get you close:
SELECT DNum, RNum, SUM(Quant) AS TotalQuantity
FROM Orders
GROUP BY DNum, RNum

Ok so some quick comments on what you have tried:
Query 1
SELECT Ord1.DNum, Ord2.DNum, SUM(Ord1.Quant + Ord2.Quant) AS TotQuant
FROM Orders AS Ord1, Orders AS Ord2
WHERE (Ord1.RNum = Ord2.RNum);
This might seem like it should work, but if you think about it it's quite a meaningless query. You are selecting two identical DNum values and SUMming two identical Quant values. A human might be able to understand what you're asking the computer to do, but the computer is perplexed.
Query 2 and Query 3 will not work, primarily because they are similar to the initial query that returns and error. They are slightly different, but essentially you are asking for the wrong thing.
Now here's what you can try:
Introducing the GROUP BY method! Woohoo!
GROUP BY is perfect for this and many other queries! As stated on the w3schools page for it:
The GROUP BY statement is often used with aggregate functions (COUNT,
MAX, MIN, SUM, AVG) to group the result-set by one or more columns.
So a query like this:
SELECT Orders.DNum, Orders.RNum, sum(Orders.Quant) as OrderQuantity
FROM Orders
GROUP BY (Orders.DNum, Orders.RNum);
To deconstruct this a little bit:
This selects the columns you want to display, and the aggregate of the Orders.Quant column you want the sum of.
Then, you group by the DNum, which is then grouped by RNum to get you the sum you are looking for.
Hope it helps!

Related

Display values that are out of scope in addition to in scope

So I have a complex situation.
I have a 3 tables:
Product
Resource Name
Resource Type
C1
Bold
E2
Crema
C2
Bold
C3
Bold
Purchase_History
Resource Name
Qty
Cust ID
Date
Batch
C1
7
123
Jun 1
324
C1
7
222
Jun 10
324
C1
7
333
Jun 11
4BZ
C1
7
124
Jun 11
4BZ
C1
7
125
Jun 11
324
C1
7
111
Jun 21
324
C2
7
55
Jun 22
A22
C2
7
1
Jun 24
A22
Inventory
Resource Name
Available
Qty
Batch
C1
1
40
324
C2
1
50
3GC
C1
2
0
4BZ
C2
1
99
A22
E2
1
99
B22
E2
2
0
C22
So I've created a query as below:
Select
p.resourcename
, ph.cust_id
, ph.batch
, case when i.available=1 then 'Yes' when i.available=2 then 'no' else ''end 'In Stock'
from product p
join purchase_history ph on ph.resource_name=p.resource_name
join inventory i on i.batch=ph.batch
where
ph.date >='Jun 1'
ph.date <='Jun 20'
I am getting the following:
Resource Name
Cust Id
Batch
In Stock
C1
123
324
Yes
C1
222
324
Yes
C1
333
4BZ
No
C1
124
4BZ
No
C1
123
324
Yes
What I would like to achieve is the below, where even though the last 2 batch and products are out of the range of transactions, we can still see them as below. I know this is a weird as but essentially the team wants to see what has been sold so far - within the date range - and all product availability status. Is this something achievable?
Resource Name
Cust Id
Batch
In Stock
C1
123
324
Yes
C1
222
324
Yes
C1
333
4BZ
No
C1
124
4BZ
No
C1
123
324
Yes
C2
n/a
3GC
Yes
C2
n/a
A22
Yes
E2
n/a
B22
Yes
E2
n/a
C22
No
you need to use left join with purchase_history table:
Select
p.resourcename
, ph.cust_id
, i.batch
, case when i.available=1 then 'Yes' when i.available=2 then 'no' else ''end 'In Stock'
from product p
join inventory i on i.resource_name=p.resource_name
left join purchase_history ph
on ph.resource_name=p.resource_name
and i.batch=ph.batch
where
ph.date >='Jun 1' and ph.date <='Jun 20'
notice I changes the order of tables for better readability.

Select sum shown null value in left join SQL statement

I have three tables and expecting the result as below but i do not know how to correct my sql statement.
select history.company,history.ghacct,rpt_revenue.revenue,rpt_revenue.other, isnull(guest.stay,0) as stay, isnull(guest.nights,0) as nights
from history
left join(select company,count(*) as stay,sum(nights) as nights from guest group by company) guest on guest.company=history.company
left join (select ghacct,sum(revenue) as revenue, sum(other) as other
from rpt_revenue group by ghacct) rpt_revenue on rpt_revenue.ghacct=history.ghacct
where history.type='c' group by history.company, history.ghacct,rpt_revenue.revenue, rpt_revenue.other,guest.stay,guest.nights order by history.company asc;
history
ghacct company type
33 JOINT LTD 10010205687 c
3B GLOBAL 10010350619 c
3E FASHION 10010244145 c
3P INT'L 10010112089 c
guest
company stay nights
33 JOINT LTD 01/01/2009 1
33 JOINT LTD 01/06/2009 1
3B GLOBAL 10/02/2019 2
3E FASHION 09/25/2008 6
3P INT'L 08/26/2009 3
3P INT'L 04/26/2010 9
rpt_revenue
ghacct revenue other
10010205687 20 10
10010205687 10 10
10010350619 30 2
10010244145 15 3
10010112089 16 8
10010112089 4 2
Result
company ghacct revenue other stay nights
33 JOINT LTD 10010205687 NULL NULL 2 2
3B GLOBAL 10010350619 NULL NULL 1 2
3E FASHION 10010244145 NULL NULL 1 6
3P INT'L 10010112089 NULL NULL 2 12
Expected result
company ghacct revenue other stay nights
33 JOINT LTD 10010205687 30 20 2 2
3B GLOBAL 10010350619 30 2 1 2
3E FASHION 10010244145 15 3 1 6
3P INT'L 10010112089 20 10 2 12
I think the main problem with your current query lies in the GROUP BY clause, which should really only be aggregating by company and account. In addition, you might want to use ISNULL for the revenue and other amount, as you are already doing so for stay and nights.
SELECT
h.company,
h.ghacct,
ISNULL(rr.revenue, 0) AS revenue,
ISNULL(rr.other, 0) AS other,
ISNULL(g.stay, 0) AS stay,
ISNULL(g.nights, 0) AS nights
FROM history h
LEFT JOIN
(
SELECT company, COUNT(*) AS stay, SUM(nights) AS nights
FROM guest
GROUP BY company
) g
ON g.company = h.company
LEFT JOIN
(
SELECT ghacct, SUM(revenue) AS revenue, SUM(other) AS other
FROM rpt_revenue
GROUP BY ghacct
) rr
ON rr.ghacct = h.ghacct
WHERE
h.type = 'c'
GROUP BY
h.company,
h.ghacct
ORDER BY
h.company;

Why is T-SQL Returning Duplicate Rows, Join Issue I Believe

The code as written below returns the appropriate customers, lockers, units and balance. However, when I add in the commented-out code it reiterates each customer's data for each club even though each customer can only be a member of one club.
USE db1
GO
SELECT [db1].[dbo].[Customer].[CustomerNumber] AS 'Customer No.'
-- ,A. ClubID AS 'Club ID No.'
,(SELECT CONCAT (SI.Locker, '-', SI.Frequency)) AS Locker
,SI.Unit AS Unit
--,[db2].[dbo].[vueClub].Club_aka AS Club
,[db1].[dbo].[Customer_Balance].[CurrentBalance]
FROM [db1].[dbo].[Customer_Balance]
JOIN [db1].[dbo].[Customer]
ON [db1].[dbo].[Customer_Balance].POSCusNo = Customer.CustomerNumber
JOIN [SQLSrv01].[ db3].[dbo].[md_Table_1] AS D
ON D.Contract_no = [db1].[dbo].[Customer_Balance]. POSCusNo
JOIN [SQLSrv01].[ db2].[dbo].[vueSoldLockers] AS SI
ON SI.CustomerID = [db1].[dbo].[Customer].CustomerID
--JOIN [db2].[dbo].[vueClub] AS A
--ON [db1].[dbo].[Customer].SiteID = A.SiteID
WHERE [db1].[dbo].[Customer_Balance].StatusCode = '1234'
ORDER BY Customer.CustomerNumber ASC
So if I run it as is I get:
Customer No. Locker Unit Current Balance
1 315 A1 456.00
2 316 A3 1204.70
3 317 B2 335.60
4 318 B4 1500.30
But if I include the commented-out code I get:
Customer No. Club ID No Locker Unit Club Current Balance
1 4 315 A1 Tigers 456.00
1 3 315 A1 Lions 456.00
2 4 316 A3 Tigers 1204.70
2 3 316 A3 Lions 1204.70
3 4 317 B2 Tigers 335.60
3 3 317 B2 Lions 335.60
4 4 318 B4 Tigers 1500.30
4 3 318 B4 Lions 1500.30
Is it because I don't have the JOIN set up properly?
Customer No. Club ID No Locker Unit Club Current Balance
1 4 315 A1 Tigers 456.00
1 3 315 A1 Lions 456.00
You are joining customer to vueClub on SiteID. Looks like the site customer 1 is in, has 2 clubs (3, 4)

MS Access, Excel, SQL, and New Tables

I'm just starting out with MS Access 2010 and have the following setup. 3 excel files: masterlist.x (which contains every product that I sell), vender1.x (which contains all products from vender1, I only sell some of these products), and vender2.x (again, contains all products from vender2, I only sell some of these products). Here's an example data collection:
masterlist.x
ID NAME PRICE
23 bananas .50
33 apples .75
35 nuts .87
38 raisins .25
vender1.x
ID NAME PRICE
23 bananas .50
25 pears .88
vender2.x
ID NAME PRICE
33 apples .75
35 nuts .87
38 raisins .25
49 kiwis .88
The vender lists get periodically updated with new items for sell and new prices. For example, vender1 raises the price on bananas to $.75, my masterlist.x would need to be updated to reflect this.
Where I'm at now: I know how to import the 3 excel charts into Access. From there, I've been researching if I need to setup relationships, create a macro, or a SQL query to accomplish my goals. Not necessarily looking for a solution, but to be pointed in the right direction would be great!
Also, once the masterlist.x table is updated, what feature would I use to see which line items were affected?
Update: discovered SQL /JOIN/ and have the following:
SELECT * FROM master
LEFT JOIN vender1
ON master.ID = vender1.ID
where master.PRICE <> vender1.PRICE;
This gives me the output (for the above scenario)
ID NAME PRICE ID NAME PRICE
23 bananas .50 23 bananas .75
What feature would instead give me:
masterlist.x
ID NAME PRICE
23 bananas .75
33 apples .75
35 nuts .87
38 raisins .25
Here is a heads up since you were asking for ideas to design. I don't really fancy your current table schema. The following queries are built in SQL Server 2008, the nearest syntax that I could get in sqlfiddle to MS Access SQL.
Please take a look:
SQLFIDDLE DEMO
Proposed table design:
vendor table:
VID VNAME
1 smp farms
2 coles
3 cold str
4 Anvil NSW
product table:
PID VID PNAME PPRICE
203 2 bananas 0.5
205 2 pears 0.88
301 3 bananas 0.78
303 3 apples 0.75
305 3 nuts 0.87
308 3 raisins 0.25
409 4 kiwis 0.88
masterlist:
ID PID MPRICE
1 203 0.5
2 303 0.75
3 305 0.87
4 308 0.25
Join queries can easily update your masterlist now. for e.g.:
When the vendor updates their prices for the fruits they provide you. Or when they stop supply on that product. You may use where clauses to add the conditions to the query as you desire.
Query:
SELECT m.id, p.vid, p.pname, p.pprice
FROM masterlist m
LEFT JOIN product p ON p.pid = m.pid
;
Results:
ID VID PNAME PPRICE
1 2 bananas 0.5
2 3 apples 0.75
3 3 nuts 0.87
4 3 raisins 0.25
Please comment. Happy to help you if have any doubts.

SQL Help With Query - Group By and Aggreate Functions

I have a query I need some help with, have been checking out a fair few tutorials but nohting I found covers this issue.
I have three joined tables, Products,ProductImagesLookUp and Images.
A product can have any number of Images and the Order of the Images for a Product are stored in ProductImagesLookUp.
I need to return a list of products with their primary Image (the one with the lowest order value).
The list looks like this
Product
Images
LookUpId FileID Order ProductTitle Price ProductId
65 2 1 Amari Summer Party Dress 29.99 7
66 1 2 Amari Summer Party Dress 29.99 7
67 3 3 Amari Summer Party Dress 29.99 7
74 4 5 Beach Cover Up 18.00 14
75 5 4 Beach Cover Up 18.00 14
76 7 6 Beach Cover Up 18.00 14
77 8 7 Beach Cover Up 18.00 14
78 9 8 Beach Cover Up 18.00 14
79 10 9 Amari Classic Party Dress 29.95 15
80 11 11 Amari Classic Party Dress 29.95 15
81 12 10 Amari Classic Party Dress 29.95 15
I want my query to pull back a list of distinct products which have the lowst Order value.
I.e. it shoudl pull back the rows with the ProductImagesLookUpId of 65 (Product 7),74 ( Product 14) and 79 (Product 15).
Thanks in advance for your help. this one has really had me pulling my hair out!
SELECT
l.LookupId,
i.FileId,
l.[Order],
p.ProductTitle,
p.Price,
p.ProductId
FROM
Products p
INNER JOIN ProductImagesLookUp l ON l.ProductId = p.ProductId
INNER JOIN Images i ON i.FileId = l.FileId
WHERE
i.[Order] = (
SELECT MIN([Order])
FROM ProductImagesLookUp
WHERE ProductId = p.ProductId
)
There is no need to group by or aggregate anything since the sub-query ensures that there is not more than a single result row for any given ProductId — the one with the lowest Order.