I have the two tables tbl_Customers and tbl_Invoices.
In tbl_Invoice table there the following columns:
• InvoiceId
• InvoiceDate
• DueDate
• CustomerId
• InvoiceAmount
• PaidAmount
• RemainingAmout
• PaidOrNot
When I generate the New Invoice, then how do I find the sum of previous not paid invoices?
My Question is that, when I print number of invoices with where clause with Invoice create Date, then how do I find the RemainingAmount of customers in newly printed invoice of each customer?
In order to get the not paid amounts, then you should get all the remaiming amount of the invoices not fully paid.
SELECT SUM(InvoiceAmount - PaidAmount)
FROM tbl_Invoices
WHERE PaidAmount < InvoiceAmount
AND CustomerId = #custID
You can add a condition on the CreateDate to be smaller than Today,
or perhaps adding a condition on the DueDay (whether it was due or not).
This part was not clear in your question.
Why can't you do this with a simple select like this:
SELECT SUM(InvoiceAmount)
FROM tbl_Invoices
WHERE PaidAmount < InvoiceAmount AND CustomerId = #custID
Related
I have a table in SQL, that looks a little similar to the table below:
[enter image description here]
My goal is to generate a first and Last Transaction report.
I want to know when did customer X make their first purchase and what is the date of their most recent purchase.
I would like to group my results by Store and add all the transaction if they happen on the same day.
For instance, if John do made 2 expenses at walmart on Jan 15th and that's their most recent transaction, I would like those two expenses to be Summed in my report.
Here is the final result I'd expect from a table like on the example above:
[enter image description here]
With what I have tried so far,
I am only getting 1 value back
The SQL looks a little similar to
Select
SN
, SID
, CustomerName
, BankAccount
, Min(TransDate)
, Max(TransDate)
, price
, store
From transaction
GROUp by
SN
, SID
, CustomerName
, BankAccount
, Min(TransDate)
, Max(TransDate)
, price
, store
I know I have to use some types of nested query to get the result(maybe) but I have been unsuccessful.
I would try and pull out the customer info you need to filter out the rest of the data. I would start with a CTE to get the MIN and MAX dates for each customer. I would then JOIN that back up to the original table and just get the records for the Customer that are on that MAX date.
I would assume you have something that is more Unique then the customer name, and if so I would use that instead. But here is what I came up with given the data you provided:
CREATE TABLE #tmp(SerialNumber int, SearialID int,CustomerName varchar(100), BankAccount int,
TranDate date, Price decimal(10,2),TracerID int,Store varchar(20))
INSERT INTO #tmp VALUES
(2,2,'Peter Smith',14564,'1/1/2021',10,756,'Kroger'),
(1,1,'John Do',12345,'1/1/2021',10,156,'Walmart'),
(1,1,'John Do',12345,'1/15/2021',5,148,'Walmart'),
(1,1,'John Do',12345,'1/15/2021',15,148,'Walmart'),
(2,2,'Peter Smith',14564,'1/12/2021',12,756,'Kroger')
;WITH CTE AS
(
SELECT Min(TranDate) FirstDate, Max(TranDate) LastDate, CustomerName
FROM #tmp
GROUP BY CustomerName
)
SELECT T.SerialNumber,T.SearialID,T.CustomerName,t.BankAccount,C.FirstDate FirstTrans, C.LastDate,SUM(t.Price) Price,T.Store
FROM #tmp T
INNER JOIN CTE C on t.CustomerName = c.CustomerName and t.TranDate = c.LastDate
GROUP BY T.SerialNumber,T.SearialID,T.CustomerName,t.BankAccount,C.FirstDate,C.LastDate,T.Store
I have a table that records the following items:
product_id
product_status
date
Products can exist in the following product statuses: pending, active, or canceled. Only one status can exist per date per product code. A status and product code is inserted for each and every day a product exists.
Utilizing SQL I'd like to be able to identify the initial cancellation dates for a product that cancels more than once in a given time frame.
i.e. if a product is active for 3 days and then cancels for 3 days and then is active again for 3 days and then cancels again for another 3 days.
I'd like to be able to identify day 1 of the 2 cancellation periods.
Thought I'd get the crystal ball out for this one. This sounds like a Gaps and Islands question. There's plenty of answers on how to do this on the internet, however, this might be what you're after:
CREATE TABLE #Sample (product_id int,
product_status varchar(10),
[date] date); --blargh
INSERT INTO #Sample
VALUES (1,'active', '20170101'),
(1,'active', '20170102'),
(1,'active', '20170103'),
(1,'cancelled', '20170104'),
(1,'cancelled', '20170105'),
(1,'cancelled', '20170106'),
(1,'active', '20170107'),
(1,'pending', '20170108'),
(1,'active', '20170109'),
(1,'cancelled', '20170110'),
(2,'pending', '20170101'),
(2,'active', '20170102'),
(2,'cancelled', '20170103'),
(2,'cancelled', '20170104');
GO
SELECT *
FROM #Sample;
WITH Groups AS (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY product_id
ORDER BY [date]) -
ROW_NUMBER() OVER (PARTITION BY product_id, product_status
ORDER BY [date]) AS Grp
FROM #Sample)
SELECT product_id, MIN([date]) AS cancellation_start
FROM Groups
WHERE product_status = 'cancelled'
GROUP BY Grp, product_id
ORDER BY product_id, cancellation_start;
GO
DROP TABLE #Sample;
If not, then see Patrick Artnet's comment.
I have an Access database with customer IDs. Each customer can have multiple orders and each order can be of a different type. I have three separate tables (Online, In-store, Payment Plan) for each order type with various amounts from each order, all are related to a customer ID. In one of the tables, there are two types of order types that amounts must be maintained separately withing the same table. I want to sum each order type in another table called Totals. I can successfully create a query to get the sums for each type based on the customer ID but I am not sure how to pull those values in my Totals table. The scenario below is repeated for multiple customers and each type is its own table---the payment plans are in a table together. I have historical data so I am limited to how I can manipulate as far as merging fields and what not.
Customer ID#: 1
Order Type: Online
Online Amount: $20.00
Order Type: Online
Online Amount: $40.00
Sum of Online Amount: $60.00
Order Type: In-store
Online Amount: $35.00
Order Type: In-store
Online Amount: $60.00
Sum of In-Store Amount: $95.00
Order Type: Payment Plan
Payment Plan 1 Amount: $30.00
Payment Plan 1 Amount: $23.00
Sum of Payment Plan 1 Amount: $53.00
Order Type: Payment Plan 2
Payment Plan 2 Amount: $35.00
Payment Plan 2 Amount: $30.00
Sum of Payment Plan 2 Amount: $65.00
In my Totals table I have a field for each type that sums the amount spent by each customer ID and then a field where all of their order types are summed into one overall total field.
I am learning as I go so any help/example is appreciated. Thank you.
Having separate tables for your different order types doesn't help. For a database it would be better to have a single table for all sales with a sale_type field.
You don't describe exactly what your tables look like, so I've had to make a couple of assumptions. If your tables contain an OrderType field then you can create a Union query to join all your sales together:
SELECT CustomerID
, OrderType
, Amount
FROM Online
UNION ALL SELECT CustomerID
, OrderType
, Amount
FROM [In-Store]
UNION ALL SELECT CustomerID
, OrderType
, Amount
FROM [Payment Plan]
If you don't have an OrderType you can hard-code the values into the query:
SELECT CustomerID
, "Online" AS OrderType
, Amount
FROM Online
UNION ALL SELECT CustomerID
, "In-Store"
, Amount
FROM [In-Store]
UNION ALL SELECT CustomerID
, "Payment Plan"
, Amount
FROM [Payment Plan]
Note - The field name is declared for the OrderType in the first Select block. You could do it in each block, but Access only looks at the first.
Like all queries, the results come in table form and can be treated as such. So now we need to list the CustomerName (I'm assuming you have a Customers table), the OrderType and the sum of the amount for that Customer & OrderType.
SELECT CustomerName
, OrderType
, SUM(Amount)
FROM Customers INNER JOIN
(
SELECT CustomerID
, OrderType
, Amount
FROM Online
UNION ALL SELECT CustomerID
, OrderType
, Amount
FROM [In-Store]
UNION ALL SELECT CustomerID
, OrderType
, Amount
FROM [Payment Plan]
) T1 ON Customers.CustomerID = T1.CustomerID
GROUP BY CustomerName
, OrderType
All sales in your three tables will have a customer within the customers table so we can use an INNER JOIN to return only records where the value appears in both tables (Customers table & result of query table).
The UNION QUERY is wrapped in brackets and given the name T1and joined to the Customers table on the CustomerID field.
We group all fields that aren't part of an aggregate function, so group on CustomerName and OrderType and sum the Amount field.
This is all you really need to do - let the query run each time you want the totals to get the most up to date values. There's shouldn't be a need to push the results to a Totals table as that will be out of date as soon as you make a new sale (or someone returns something).
If you really want to INSERT these figures into a Total table just add a first line to the SQL:
INSERT INTO Total (CustomerName, OrderType, Amount)
Here is a dirty workaround, though I think there might be a more direct solution to it.
You could create an output table (I broke it down to ID, Online, InStore and Total) and use DSum functions within an UPDATE query.
UPDATE tbl_Totals SET
Total_InStore = DSum("Amount", "tbl_InStore", "Customer_ID = " & Customer_ID),
Total_Online = DSum("Amount", "tbl_Online", "Customer_ID = " & Customer_ID),
Total = DSum("Amount", "tbl_InStore", "Customer_ID = " & Customer_ID) + DSum("Amount", "tbl_Online", "Customer_ID = " & Customer_ID)
I have a column called balance and another column called repnum. Repnum represents a representative who's taken care of customers. I've managed to grab the customers name, the specific representative i'm looking for (15), and I know I can grab the balance by taking out (sum(balance)) but what I want to do is get the sum of the balance column with only representative 15's orders. This is what I currently have thought up:
select customername, repnum, sum(balance) balance from customer where repnum = '15'
Add an over clause to the sum function to prevent the need for group by:
Select customername,
Repnum,
Sum(balance) over(partition by repnum) balance
From customer
Where repnum = 15
I think you can just add group by customername, repnum to the end of your query.
I'm sorry, I'm newbie using T-SQL AND I would like to know how can i get value that doesn't occurs more than once. I already tried this but it didn't work.
SELECT DISTINCT *
FROM Orders
WHERE PmtType NOT IN ('VISA','DISC','FUNDING','DEALER CHECK','MC'
,'AMEX','BONUS POOL','DLR CK - NET30'
,'WIRE','MO','EXCHANGE','ONLINE','NULL')
AND OrderDate BETWEEN '2014-03-01 00:00:00'
and '2015-03-01 00:00:00'
AND CompanyId IN ('1311','8390','8394','8396','8397','8399','3966',
'8407','8408','8315','8411','8413','8414','8416'
,'8419','4850','8426','8428','8429','8430')
What I'm trying to get is this. Companies that receive Free Demos. Which the PmtType would be free, but never purchased a product.
If the customer never purchase a product the customer Id shouldn't appear in the
PmtType IN ('VISA','DISC','FUNDING','DEALER CHECK'
,'MC' ,'AMEX','BONUS POOL','DLR CK - NET30'
,'WIRE','MO','EXCHANGE','ONLINE','NULL')
if i read the question correctly you want to know which IDs have only 1 order, this will do it. I used generic field name as you didnt specify what "value" you want to find...
EDIT: added the NOT EXISTS clause after OP Comment, you may no longer need the group by, that is up to you...
SELECT CompanyId --add fields here as needed.
,Count(*) [Occurences]
FROM Orders o
WHERE PmtType = 'FREE'
AND NOT EXISTS (SELECT CompanyId
FROM Orders io
WHERE o.CompanyId = io.CompanyId
AND PmtType <> 'FREE' )
GROUP BY CompanyId --add fields here as needed.
HAVING Count(*) = 1 --leave this out to see how many free demos each company got.