I've been looking for this answer for hours without finding anything at all on this subject.
I'm trying to get a pivot table from the "Sells" table that displays :
- as header fields, the name of each seller in my shop
- as rows, each month of the year
- as data the sum of their sells for each month
The only issue I have is that the headers are populated with ID instead of the name of the sellers.
For example, instead of showing this :
Month | Steve | Joe
January | 5000$ | 600$
February | 400$ | 400$
It keeps showing the ID related to each seller:
Month | 1 | 2
January | 5000$ | 600$
February | 400$ | 400$
Here is my query :
TRANSFORM Sum(Sells.Ca) AS [Monthly sells]
SELECT DISTINCTROW Format$(Sells.DateSold,'mm - mmmm') AS Month
FROM Sells
GROUP BY Sells.DateSold
PIVOT Sells.Seller
Thank you very much for your help and your time.
EDIT:
As #WolfgangKais mentionned in the comments, I forgot to mention that the Seller field is a lookup field, that's why it only shows the first value of the lookup field, hence the ID and not the name.
As stated by #June7 and #Wolfgang Kais, I had to include the Sellers Table in the query in order to get each seller's name instead of their ID, thank you very much for the lead.
This was done by :
Constructing a temporary table containing rows populated by sellers name, amount sold and date of sell:
SELECT Sellers.Name AS Seller, Sells.Ca AS Amount, Sells.DateSold AS Month
FROM Sells
INNER JOIN Sellers ON Sells.Seller = Sellers.ID
Including this temporary table into my first pivot query (In the FROM part):
TRANSFORM SUM(TempTable.Amount) AS [Monthly Sells]
SELECT Format$(TempTable.Month, 'mm - mmmm') AS Month
FROM(
SELECT Sellers.Name AS Seller, Sells.Ca AS Amount, Sells.DateSold AS Month
FROM Sells
INNER JOIN Sellers ON Sells.Seller = Sellers.ID
) AS TempTable
GROUP BY Temptable.Month
PIVOT Temptable.Seller
Related
I have one table of tbl_order where columns are :
id_order
username
delivery_date etc...
and other table tbl_order_foods where columns are :
id_order
id_food
food_quantity etc
Here the sample pic of tbl_order table
and tbl_order_foods table
Here i am want to select all the foods with quantity with price and unit based on delivery_date.
Ex: Suppose On 2020-04-18 there are 3 orders where foods: tomato's are ordered total 15 kg (3 orders * 5 quantity * food_min_unit_amount * unit) and so on others foods.
how i can get the foodlist of total ordered quantity based on delivery_date
The method you need is the GROUP BY keyword.
SQL grouping works on the given attributes. According to your question this would be the delivery_date. In the projection (the attributes following the SELECT keyword) you then can use attributes you state after the GROUP BY keyword and aggregation functions e.g. SUM and MAX.
Based on your question you could get the total price for all orders on the given date like this:
SELECT order.delivery_date, SUM(food.food_quantity) as amount, SUM(food.food_total_price) as revenue
FROM tbl_order as order
INNER JOIN tbl_order_foods as food ON order.id_order = food.id_order
GROUP BY order.delivery_date
This would result in a list like this:
date | amount | revenue
------------------------
05.01| 10 | 800.00
I don't know whether this is what you wish. If you also want to split it into order positions then you would GROUP BY the food_name as well and add it to the projection which then results in the SUM grouped by the orders on a given day of a given product.
SELECT order.delivery_date, food.food_name, SUM(food.food_quantity) as amount, SUM(food.food_total_price) as revenue
FROM tbl_order as order
INNER JOIN tbl_order_foods as food ON order.id_order = food.id_order
GROUP BY order.delivery_date, food.food_name
Which would result in something like this.
date | food_name | amount | revenue
-----------------------------------
05.01| Tomato | 10 | 800.00
05.01| Apple | 5 | 400.00
Check out GROUP BY with the SUM function, a good article from Tutorialspoint.com is here. The only difference is that you are performing a JOIN to create the resulting table.
SELECT DISTINCT [f.id_food], [o.delivery_date], SUM(f.food_quantity) as [delivered_sum_qty], SUM(f.food_total_price) as [sum_food_total_price]
FROM tbl_order o LEFT JOIN tbl_order_foods f
ON [o.id_order] = [f.id_order]
GROUP BY [o.delivery_date];
If you need it, a pretty clear explanation of how to use JOIN is here as well.
I have two tables in SQL, one that contains product_id, products_name, department_name, and product_sales and one that has department_id, department_name, and over_head_costs.
I want to be able to find the sum of all sales (grouped by department_name in table 1) and subtract the over_head_costs from table 2 so that I know how profitable a department is. Then I want to output the information like:
department_id, department_name, over_head_costs, product/department sales, total_profit.
I've been searching for like 2-3 hours. I've messed around with joins (which I'm pretty sure is how to solve this) and found the SUM function, which achieves summing (but not by department) and honestly, even if I'd seen the solution I wouldn't know it. I'm just really struggling to understand SQL.
SELECT SUM(products.product_sales), department_id, departments.department_name, over_head_costs
FROM products, departments
WHERE products.department_name = departments.department_name;
This is my most recent query and the closest I've gotten, except it only returns one department (I currently have 3).
This is roughly what I’d like it to look like:
Table 1 (products):
ID ITEM DEPARTMENT SALES
1 Hammer Tools 40
2. Nails Tools 40
3. Keyboard Computer 80
Table 2 (departments):
ID DEPARTMENT COST
1 Tools 20
2. Computer 30
Output:
ID DEPARTMENT COST SALES PROFIT
1 Tools 20 80 60
2. Computer 30 80 50
I'm not really sure what else to try. I think I'm just not understanding how joins and such work. Any help would be greatly appreciated.
You can try to use SUM wiht group by in a subquery. then do join.
Query 1:
SELECT d.*,
t1.SALES,
(t1.SALES - d.COST)PROFIT
FROM (
SELECT DEPARTMENT,SUM(SALES) SALES
FROM products
GROUP BY DEPARTMENT
) t1 JOIN departments d on d.DEPARTMENT = t1.DEPARTMENT
Results:
| DEPARTMENT | COST | SALES | PROFIT |
|------------|------|-------|--------|
| Tools | 20 | 80 | 60 |
| Computer | 30 | 80 | 50 |
I am using SQL and here is the scenario I am stuck with
Table A
SubscriptionID | Club | Sum_Of_Billings_Of_All_Month | EventID
Table B:
Cost | EventID
Table A left join Table B on EventID (To track the cost of each subscription)
Result
SubscriptionID | Club | Sum_Of_Billings_Of_All_Month | EventID | Cost
I want to break down the Sum_Of_Billings_Of_All_Month into per day billings. i.e. for each subscription, I want the breakdown of billings per day of the month. For that I will group by Sum_Of_Billings_Of_All_Month instead of subscriptionID.
Consequence
If I group by days of billing, upon joining I will get duplicates of subscriptionIDs and the eventIDs will be duplicated in rows multiple time which will then count the cost multiple times as well.
What I want:
In the same query, I want to be able to group by SubscriptionID so I can keep the unique subscriptions per row with their cost.
But one of the other requirement is that I want to know the breakdown of the billings as well to calculate the breakeven and other metrics in the same query
Here is the actual sample data
Table A
idCustomerSubscription | ClubID | EventId | BillingDate| FinalRevenue
33562784 | 56180001| 5y6m600np1fg | 5/31/2017 | 512
Table B
EventId |Cost
5y6m600np1fg |200
Table A join B left join on eventId (Group by SubscriptionID
idCustomerSubscription |ClubID |EventId |BillingDate| FinalRevenue | Cost
33562784 | 56180001 |5y6m600np1fg| 5/31/2017 | 512 |200
It serves the purpose because each subscription has one cost which is unique BUT it on the other hand, this kind of query will not give me breakdown of dates of billings (I need it for the breakeven calculation)
Table A join B left join on eventId (Group by billingdate
idCustomerSubscription| ClubID |EventId | BillingDate| FinalRevenue |Cost
33562784 | 56180001| 5y6m600np1fg |5/30/2017 |510 |200
33562784 | 56180001| 5y6m600np1fg |5/31/2017 |2 |200
This would give me the breakdown of the dates which i need for breakeven (510 on 30th and 2 on 31st) but it will make the cost duplicated (400 is the cost instead of 200)
I want to find out a SQL magic where I can keep the number of unique subcriptions per row and some way to track the billing dates of each subscriptions in the same query (without grouping it by date because it will make the rows duplicated). Is it possible ?
Perhaps some way where when the eventids are joined and its grouped by date, it doesnt duplicate the cost and count only one cost per eventid?
I hope you will get your desired result with below query. Try to modify your group by operation for mn (alias name) table.
select mn.idCustomerSubscription,mn.ClubID,mn.EventId,mn.BillingDate,mn.FinalRevenue,sq.cost
from tableA Mn left join (select idCustomerSubscription,max(cost) cost, min(billingDate) billingDate from tableA a left join tableB b on a.eventid=b.eventid group by idCustomerSubscription) sq on mn.idCustomerSubscription=sq.idCustomerSubscription and mn.billingDate=sq.billingdate
group by mn.idCustomerSubscription,mn.ClubID,mn.EventId,mn.BillingDate
I have this table :
TICKETID | PRICE | NUMBER
So for each ticketid, the player can pay a price for each number on the ticketid.
So if the player wants to pay 1$, 3$ and 4$ for numbers 22,23 and 24 for ticketid 25, then the table will look like this :
TICKETID | PRICE | NUMBER
25 | 1 | 22
25 | 3 | 23
25 | 4 | 24
I want to select a random ticket that has TOTAL PRICE >50, to make it receive a prize.
I also want that the randomization to be fair, and that when doing this draw, each ticket would have only 1 apparition rate. If I don't use DISTINCT or GROUPBY, then a ticketid with 10 numbers will have more chances to get drawn than a ticket with 2 numbers.
I tried this but it's not working:
SELECT DISTINCT(ticketid),SUM(price) FROM table
WHERE SUM(price)>50 GROUP BY ticketid
I get the error message
invalid usage of GROUP BY function
Can anybody help?
What you want is the "HAVING" clause which is applied to any possible candidate records AFTER the group by aggregations have been processed. The Having is applied THEN and either included (or not) in the final result set.
SELECT
ticketid,
SUM(price) TotalPrice
FROM
table
group by
TicketID
HAVING
sum(price) > 50
Working in MS Access 2003 SP3: I have a query that I am running to find what 'cars' were sold with a date after the delivery date. I have thousands of rows. When it is all said and done, I want to just have a handful of rows for each 'car' and then the oldest date. Any suggestions?
CAR DATE ORDERED DATE DELIVERED CUSTOMER NUMBER DATE SOLD
FORD MUSTANG 20061002 20080413 ABC123 20080422
FORD MUSTANG 20061002 20080413 ABC124 20080429
CHEVY IMPALA 20061002 20080413 ABC125 20080505
This could be better if you had an ID field:
DELETE
FROM Cars
WHERE Cars.DATESOLD Not In (
SELECT TOP 5 DateSold
FROM Cars c
WHERE c.Car=Cars.Car
ORDER BY DateSold DESC)
And Cars.DATESOLD Not In (
SELECT TOP 1 DateSold
FROM Cars c
WHERE c.Car=Cars.Car
ORDER BY DateSold)
If there are duplicate dates, you will end up with more than 5 records.