I have the following db schema (i'm only mentioning the columns for each table necessary for the query in mind):
bills
-------
id
amount (decimal)
collection_case_id
collection_case
------------------
id
payments
----------
id
bill_id
amount (decimal)
type (char(2)) - "CH" stands for check payment, field used for polymorphism
check_payments
---------------
payment_id
For a set of collection cases, I need to get the total interest earned from check payments.
I am currently doing these calculations in memory after retrieving all the bill records for my set of collection case criteria. For each bill I simply add the sum of checks received - bill amount if sum of checks received is greater than bill amount.
for instance my total received query looks like this (collection cases 1 & 2):
select sum(payment.amount) as received
from bills bill
cross join payments payment inner join check_payments checkpayment
on
payment.id=checkpayment.payment_id
where payment.type='CH'
and payment.bill_id=bill.id
and (bill.collection_case_id in (1 , 2))
Not really sure if this is what you meant.
select IF(sum(payment.amount) > bill.amount, sum(payment.amount)-bill.amount, 0) as interest
from bills bill
cross join payments payment inner join check_payments checkpayment
on
payment.id=checkpayment.payment_id
where payment.type='CH'
and payment.bill_id=bill.id
and (bill.collection_case_id in (1 , 2))
Related
Here is the structure of 1st Table called Product.
PRODID PDESC PRICE CATEGORY DISCOUNT
101 BALL 10 SPORTS 5
102 SHIRT 20 APPAREL 10
Here is the structure of 2nd table called SaleDetail.
SALEID PRODID QUANTITY
1001 101 5
1001 101 2
1002 102 10
1002 102 5
I am trying to get total sales amount for each product by joining 2 tables. Here is the SQL i tried but its not giving correct result.
select a.prodid,
(sum((price - discount))),
sum(quantity),
(sum((price - discount))) * sum(quantity)
from product a
join saledetail b on a.prodid = b.prodid
group by a.prodid
2nd column of the query is giving incorrect final price. Please help me correct this SQL.
Please find an indicative answer to your question in the fiddle.
A problem stems from the aggregation of the difference of price. In case that the same product has two different prices, then these prices would be aggregated to one.
Moreover, you multiple the sums of the prices and quantities, while you need to perform the calculation on every sample. Look at the answer by #DanteTheSmith.
You might consider to use the SaleDetail table on the left side of your query.
SELECT SD.PRODID,
P.Price-P.Discount AS Final_Price,
SUM(SD.QUANTITY) AS Amount_Sold,
SUM((P.Price-P.Discount)*SD.QUANTITY) AS Sales_Amount
FROM SaleDetail AS SD
JOIN Product AS P
ON SD.PRODID = P.PRODID
GROUP BY SD.PRODID, P.Price-P.Discount
It would help if you built the example in SQL fiddle or gave the creates for the tables, but if I have to guess your problem is:
(sum((price - discount))) * sum(quantity)
needs to be:
sum((price - discount) * quantity)
(price - discount) * quantity is the function you wanna apply PER ROW of the joined table then you wanna add all those up with SUM() when grouping by prodid.
Furthermore, you can notice that (price - discount) needs to be done ONLY ONCE PER ROW so a quicker version would be to do:
(price-discount) * sum(quantity)
That would give you the total money earned for that product across all the sales you made, and I am guessing this is what you want?
I just notice you have a problem with 2nd column, dunno if that has been in question all along:
(sum((price - discount)))
Why are you summing? Do you want the money earned per product per unit of the product? Well guess what, your price is the same all the time, same as your discount so you can simply go with:
(price-discount) as PPP
NOTE: This assumes the discount is numerical (not percentage) and is applicable to all your sales, also the price is forever the same all which is not real life like.
Everything looks in order for the code to run, but the code isn't showing any rows. So, i must be doing something wrong. I can't figure out where the problem is. The problem from my instructor is:
Use the AP database
Vendor name from the vendor table
Vendor Contact First Name and Vendor Contact Last Name from the vendor table but I need them concatenated together with a space between the names
Invoice Date from the invoice table
Only the day of from the Invoice Date
Invoice Number from the invoice table
The third and fourth characters from the Invoice Number
Line Item Amount from the invoice line items table
Calculate the commission which is the Line Item Amount * 15% and make it ONLY two decimals
The FROM is the Vendors table do JOINS on the others
The WHERE is where the Line Item Amount is greater than $2000 and the Invoice Date is between July 1, 2014 and July 31st, 2014 and I only want the ones that have either a 9 or a 2 in the Invoice Number
Sort by Invoice Date
// This is the only information he's given me for this assignment. ^
I've tried to join different columns together in different orders/joining tables in different orders.
select vendor_name as vendor, concat(first_name, ' ', last_name) as Contact,
DAY(invoice_date) as ofday, invoice_date,
SUBSTRING(invoice_number, 3,2) as thirdFourth,
line_item_amount,round(line_item_amount*.15, 2) as Commission
from vendors v
JOIN vendor_contacts vc
ON v.vendor_id = vc.vendor_id
JOIN INVOICES INV
ON VC.VENDOR_ID = INV.VENDOR_ID
JOIN invoice_line_items ILI
ON INV.invoice_id = ILI.invoice_id
where line_item_amount > 2000
and invoice_date between '2014-7-1' and '2014-7-31'
and (invoice_number =9 OR invoice_number =2)
expected results :
https://imgur.com/E81ix3o
At the moment you are asking specifically for invoice_number 9 or 2. You don't have an invoice_number of 9 or 2 If you want invoice_numbers with 9 or 2 in you will need
invoice_number like '%9%' or invoice_number like '%2%'
Each department is supposed to have only one statement per monthly billing cycle.
My goal is to figure out how many departments have been hit with more than one billing statement (having a value greater than $0.00) within the same billing cycle.
CONTEXT:
My current query is set to check only departments that are supposed to be billed monthly.
Department table has a one-to-many relationship with Statement table (a department is expected to have one or more statements)
Statement table has a one-to-many relationship with Trans table (a statement is expected to have one or more transactions)
Each billing statement has its own statement_close_date
c.type=‘periodic’ refers to a bill that only occurs once per billing cycle
d.period=1 represents accounts that are billed monthly
s.status=‘closed’ represents only closed statements
d.exp_date represents billing expiration date
v.status=‘active’ and d.status=‘active’ are meant to ensure that only active departments are being queried.
I also tried searching between specific expire dates on a per account basis.
The problem with my query is that it outputs the total number of billing statement_close_dates with a value greater than $0.00, instead of only checking for multiple occurrences within a billing cycle.
How can this query be modified to only output departments with more than one instance of a bill consisting of a periodic type charge greater than $0.00 within each department’s billing cycle?
QUERY:
SELECT s.department_id, s.statement_id, COUNT(s.statement_close_date) AS sd,
t.trans_id, from_unixtime(s.statement_close_date)
FROM statement s
INNER JOIN trans t
ON t.statement_id=s.statement_id
INNER JOIN cde c
ON t.cde=c.cde
INNER JOIN department d
ON s.department_id=d.department_id
WHERE from_unixtime(s.statement_close_date) BETWEEN
DATE_SUB(from_unixtime(d.exp_date), INTERVAL 1 MONTH) AND
from_unixtime(d.exp_date)
AND d.period=‘1’
AND s.status='closed'
AND t.dollars>0
AND c.type='periodic'
GROUP BY s.statement_id DESC
HAVING sd>1
SAMPLE OUTPUT:
department_id statement_id sd trans_id statement_close_date
1719712 9351464 3 98403043 2018-09-24
1719709 9351463 2 98403026 2018-09-24
1719708 9351462 2 98403010 2018-09-24
1719665 9351457 3 97374764 2018-09-24
I'm using Mysql (not MSSQL) database and bumped onto a problem I seem to be unable to solve. I would very much appreciate your help finding a solution.
I'd like to create a view using two tables, as described below:
1. product_in
product_code
received_time
received_amount
2. product_out
product_code
delivery_time
delivered_amount
The “view” should provide the following:
product_code
received_time
received_amount
of_which_delivered
My problem is that product_out is to be administered to the first incoming data (FIFO: first in first out), but since the amount delivered is either more or less than the received amount, I do not know how to calculate the “of_which_delivered”.
So far, I managed to put into order the incoming data, and sum up the outgoing (delivered) goods using SUM.
SELECT
sn,
product_code,
received_time,
received_amount,
delivered_amount
FROM
( SELECT
received_time,
received_amount,
#rend2 := If( #rend1 = product_code, #rend2 + 1, 1) as sn,
#rend1 := product_code AS product
FROM
product_in,
( SELECT #rend1 := 0, #rend2 := 0 ) AS tt
ORDER BY
product_code,
received_time ) AS k
LEFT JOIN
( SELECT
product_code AS prdct,
SUM(delivered_amount) AS delivered_amount
FROM
product_out
GROUP BY
product_code ) AS b
ON aru = product_code
I have not succeded in creating the loop that would make it possible to analyze if the output amount is more, or less than the received amount on a given day, and if more, then the difference be added to the received amount of another day.
To be more precise, here is an example:
Product Date Qty
nr.1 Sep 2 500
nr.1 Sep 3 300
nr1. Sep 4 200 on the 4th.
900 pcs were delivered out on the 5th.
In this case we should see the following in the view:
Product Action Date Qty
nr.1 received Sep 2 500 (delivered all 500)
nr.1 received Sep 3 300 (delivered all 300)
nr.1 received Sep 4 200 (only 100 delivered)
I would be very grateful to anyone who could help me find a solution!
Sorry no query adjustment for you, but... having worked with accounting systems in the past, your database structure appears short on a better handling of the in/out FIFO method (or even LIFO). What the underlying accounting system had was a inventory table for all receipts (abbreviated)
Table: ItemTrans
ItemTransID (auto-increment ID for any transaction)
ItemID (item id of the inventory item)
Status (status, such as In, Our or Inventory Adjustment)
Date (date of the activity)
Qty (quantity)
QtyUsed (running total column as inventory was used up)
As items were sold or adjustments. the Sales Details table would show which ItemTrans record the quantities were used for. So, if you had inventory on hand as you have in your sample, the sales order detail line would show the 900. The inventory used table would show which specific ItemTransID the quantities were allocated from and how many from said block, thus showing what your intended activity of release of actual product was at the time of sale.
This way, you don't have to recreate what inventory was what at a given point in time. Just query the sales order details and which items they were pulled from to get the data and how many from each block of receipt it went against.
This simplifies the process of generating the COGS (cost of goods sold) as would be reported to the General Ledger from a Sub-journal such as Accounts Receivable (Sales Orders) activity.
Do you have the ability to introduce such adjustments to your database structures?
I have two tables, [Party] and [Invoice], in an Access database. I want to summarize all party balances. Here is my query so far:
select
Party.AccountCode,
Party.AccountDescription,
OpeningBalance+sum(invoiceAmount) as balance,
invoiceDate
from Party,Inovoice
where party.accountCode=Inovice.AccountCode
and invoiceDate>=01-01-2013
and invoiceDate<=30-06-2013
group by
Party.AccountCode,
Party.AccountDescription,
invoiceDate
This query returns the balance for only the two parties that appear in the [Invoice] table: TOM and JHONS. I want to display the balance for all 4 parties:
Use two queries. The first to calculate the total invoice amount and the second for the party balances
qrySumInvoiceAmounts:
SELECT
AccountCode
sum(invoiceAmount) as InvoiceBalance,
FROM Invoice
group by
AccountCode,
WHERE invoiceDate>= #01-01-2013#
and invoiceDate<= #30-06-2013#
qryPartyBalance:
SELECT
Party.AccountCode,
Party.AccountDescription,
OpeningBalance + InvoiceBalance,
from Party LEFT JOIN qrySumInvoiceAmounts
ON party.accountCode=qrySumInvoiceAmounts.AccountCode