Transferring Data from one table to another - sql

I need help with my sql code, is there a way for me to transfer the data from "AS subtotal" from the first SELECT statement to the "receipt.totalAmount" from the second SELECT statement. Kind of new with sql I tried to look it up online but I didn't see any solution for it. I can't declare subtotal from the first SELECT statement to the second SELECT statement. Also is it possible to sum up all the subtotals to the total column?
SELECT productServices.productId, productServices.proPrice, orders.orderId, orders.quantity, productServices.proPrice*orders.quantity AS subtotal , orders.dateOrdered
FROM productServices
JOIN orders
ON productServices.productId=orders.productId
SELECT receipt.receiptNo, receipt.customerId, receipt.orderId, receipt.employeeId, receipt.totalAmount, receipt.paymentMethod, receipt.dateOfPurchase
FROM receipt
JOIN customerInfo ON customerInfo.customerId=receipt.customerId
JOIN employeeInfo ON employeeInfo.employeeId=receipt.employeeId
JOIN orders ON orders.orderId=receipt.orderId

You need to write it into a single select statement. Something like this. Or use inner queries to get what you need.
SELECT receipt.receiptNo, receipt.customerId, receipt.orderId, receipt.employeeId, receipt.totalAmount, receipt.paymentMethod, receipt.dateOfPurchase,
productServices.productId, productServices.proPrice, orders.orderId, orders.quantity, productServices.proPrice*orders.quantity AS subtotal , orders.dateOrdered
FROM receipt
JOIN customerInfo ON customerInfo.customerId=receipt.customerId
JOIN employeeInfo ON employeeInfo.employeeId=receipt.employeeId
JOIN orders ON orders.orderId=receipt.orderId
JOIN productServices on productServices.productid = orders.productid

Related

SQL dividing a count from one table by a number from a different table

I am struggling with taking a Count() from one table and dividing it by a correlating number from a different table in Microsoft SQL Server.
Here is a fictional example of what I'm trying to do
Lets say I have a table of orders. One column in there is states.
I have a second table that has a column for states, and second column for each states population.
I'd like to find the order per population for each sate, but I have struggled to get my query right.
Here is what I have so far:
SELECT Orders.State, Count(*)/
(SELECT StatePopulations.Population FROM Orders INNER JOIN StatePopulations
on Orders.State = StatePopulations.State
WHERE Orders.state = StatePopulations.State )
FROM Orders INNER JOIN StatePopulations
ON Orders.state = StatePopulations.State
GROUP BY Orders.state
So far I'm contending with an error that says my sub query is returning multiple results for each state, but I'm newer to SQL and don't know how to overcome it.
If you really want a correlated sub-query, then this should do it...
(You don't need to join both table in either the inner or outer query, the correlation in the inner query's where clause does the 'join'.)
SELECT
Orders.state,
COUNT(*) / (SELECT population FROM StatePopulation WHERE state = Orders.state)
FROM
Orders
GROUP BY
Orders.state
Personally, I'd just join them and use MAX()...
SELECT
Orders.state,
COUNT(*) / MAX(StatePopulation.population)
FROM
Orders
INNER JOIN
StatePopulation
StatePopulation.state = Orders.state
GROUP BY
Orders.state
Or aggregate your orders before you join...
SELECT
Orders.state,
Orders.order_count / StatePopulation.population
FROM
(
SELECT
Orders.state,
COUNT(*) AS order_count
FROM
Orders
GROUP BY
Orders.state
)
Orders
INNER JOIN
StatePopulation
StatePopulation.state = Orders.state
(Please forgive typos and smelling pistakes, I'm doing this on a phone.)

Count(*) with inner join and group by

I have 2 tables.
I need to get the number of counts with id from table 2 and get the name for the id from table 1.
I tried the following code. Didn't work!
select orders.CustomerID, customers.ContactName , count(*)
from Orders
left join customers on Customers.CustomerID= Orders.customerid
group by Orders.customerid;
Pls explain my shortcomings if possible.
When grouping the group by section of the query needs to mention all columns tat appear outside of an aggregate like COUNT. You're missing the ContactName here.
A fixed version:
select orders.CustomerID, customers.ContactName , count(*)
from Orders
left join customers on Customers.CustomerID= Orders.customerid
group by Orders.customerid, customers.ContactName;
Alternatively you can group by ID alone and then make the join like this:
With OrderCounts AS
(
select orders.CustomerID , count(*) AS OrderCount
from Orders
group by Orders.customerid
)
SELECT OrderCounts.CustomerID
, customers.ContactName
, OrderCounts.OrderCount
FROM OrderCounts
left join customers on Customers.CustomerID= OrderCounts.CustomerID
The first version is shorter and easier to type. In some scenarios the second version will run faster as the group by occurs on a single table & column.
For the second to give the same results CustomerID must be unique in the customers table otherwise it will produce duplicates (but if that's the case the first example would double count orders).

Creating a nested query to filter from the inital query

I am attempting to create a nested query so that the query select all ordernumbers and orderid from the invoice items and then selects the items that were sub rented.
select
do.orderid, do.orderno, ot.masteritemid, ot.qty
from dealorder do
inner join ordertran ot on do.orderid=ot.orderid and ot.orderid='A00M5BGA'
where ot.vendorid<>''
Select orderno, orderid from invoiceitemview where invoiceno='T646692'
I have tried an inner join but it does not seem to work. The first query gives me 6 items which is correct, however if I perform the join, it seems to be getting items that do not belong to the order. Hence, How would I create a nested query to get all items from the second query and then filter using the first query.
This sounds like what you are looking for
select
do.orderid, do.orderno, ot.masteritemid, ot.qty
from dealorder do
inner join ordertran ot on do.orderid=ot.orderid and ot.orderid='A00M5BGA'
inner join (
Select orderno, orderid from invoiceitemview where invoiceno='T646692'
) tmp ON tmp.orderno=do.orderno AND tmp.orderid=do.orderid
where ot.vendorid<>''
Try this.
select do.orderid, do.orderno, ot.masteritemid, ot.qty
from (Select orderno, orderid from invoiceitemview where invoiceno='T646692') inv
inner join dealorder do inv.orderid=do.orderid
inner join ordertran ot on do.orderid=ot.orderid and ot.orderid='A00M5BGA'
where ot.vendorid<>''

SQL Nested Query Calculation

SELECT *,
(select SUM(sl.priceeach*sl.qty) as 'tot'
from salesline sl where sl.soid=so.soid) as 'total',
so.total,
so.discount,
so.tax
from salesorder so
I am trying to figure out this query but I couldn't display the total in another coloumn
to display the tax included and discount minused data
ERROR : #1054 - Unknown column 'so.total' in 'field list'
whats wrong with my query ?
First you do not want to use a correlated subquery for this. In fact, you should alost never use them at all as they process row-by-agonizing-row like a cursor.
A CTE or derived table will do the job.
SELECT a.total,
so.discount,
so.tax
FROM salesorder so
JOIN
(SELECT sl.soid,SUM(sl.priceeach*sl.qty) AS 'total'
FROM salesline sl GROUP BY sl.soid) A
ON A.soid = so.soid
Now total is an available column to use in other calculations in your query such as:
SELECT a.total,
so.discount,
so.tax,
so.tax*a.total as TaxableAmount
FROM salesorder so
JOIN
(SELECT sl.soid,SUM(sl.priceeach*sl.qty) AS 'total'
FROM salesline sl GROUP BY sl.soid) A
ON A.soid = so.soid

Query does not shows a result if there is one row with Sum() function

I am trying to create a Office Access program to monitor my depts.
I have a table that contains that how much I owe to someone named tbl_depts.
I have another table that contains my payments named tbl_payments.
here is my syntax:
SELECT DISTINCTROW
tbl_depts.who,
tbl_depts.dept,
Sum(tbl_payments.payment) AS [Paid],
(tbl_depts.dept - [Paid]) AS remaining
FROM tbl_depts INNER JOIN tbl_payments ON tbl_depts.[ID] = tbl_payments.[dept_ID]
GROUP BY tbl_depts.who;
But there is a problem. If there is only one payment for a dept, query showing empty. But this query works perfect if there is two payment for that dept.
What should I do?
how about using LEFT JOIN, when using INNER JOIN be sure that dept_ID exists on both tables.
SELECT DISTINCTROW
tbl_depts.who,
tbl_depts.dept,
Sum(tbl_payments.payment) AS [Paid],
(tbl_depts.dept - [Paid]) AS remaining
FROM tbl_depts LEFT JOIN tbl_payments
ON tbl_depts.[ID] = tbl_payments.[dept_ID]
GROUP BY tbl_depts.who, tbl_depts.dept, (tbl_depts.dept - [Paid]);
Your query above wont even run - the grouping is wrong.
This works:
SELECT tbl_depts.ID, tbl_depts.who, tbl_depts.dept, Sum(tbl_payments.payment) AS paid, [dept]-[payment] AS remaining
FROM tbl_payments INNER JOIN tbl_depts ON tbl_payments.dept_ID = tbl_depts.ID
GROUP BY tbl_depts.ID, tbl_depts.who, tbl_depts.dept, [dept]-[payment];