Tying in public purchase records - sql

I'm trying to get a list of purchases for work. Currently, what we're doing is tracing product orders based on what our customers have said they've bought. For instance, Steve says he has bought iPhones on the 3rd Jan 2022, the 15th Dec 2021 and the 1st of Nov 2021.
What I'm currently doing is a very arduous task - three separate queries, extracting them all, then removing duplicates in Excel to then analyze the account ID's that have bought on those three dates.
This in of itself takes time, but also, some customers buy 5, 7, 10 products etc so it can become quite difficult.
select tt.order_time, tt.from, tt.to, tt.value/1e9, tt.orderID
from transactiontable tt
where right(tt.data::varchar,8) = '9092fcb5'
and left(tt.data::varchar, 10) in ('\xfb3bdb41', '\x7ff36ab5')
and tt.contract_address = '\9092fcb5'
and tt.order_time between '2022-05-09 00:00' and '2022-05-09 23:59'
Does anyone have any help on how I can essentially take X number of queries and then only show me the distanct "from" addresses for each overall query?
Thanks!

Related

Is there a simple line (or two) of code that will pull records before a minimum date in another table?

I want to pull Emergency room visits before a members first treatment date. Everyone as a different first treatment date and none occur before Jan 01 2012.
So if a member has a first treatment date of Feb 24 2013, I want to know how many times they visited the ER one year prior to that date.
These min dates are located in another table and I can not use the Min date in my DATEADD function. Thoughts?
One possible solution is to use a CTE to capture the visits between the dates your interested in and then join to that with your select.
Here is an example:
Rextester
Edit:
I just completely updated my answer. Sorry for the confusion.
So you have at least two tables:
Emergency room visits
Treatment information
Let's call these two tables [ERVisits] and [Treatments].
I suppose both tables have some id-field for the patient/member. Let's call it [MemberId].
How about this conceptual query:
WITH [FirstTreatments] AS
(
SELECT [MemberId], MIN([TreatmentDate]) AS [FirstTreatmentDate]
FROM [Treatments]
GROUP BY [MemberId]
)
SELECT V.[MemberId], T.[FirstTreatmentDate], COUNT(*) AS [ERVisitCount]
FROM [ERVisits] AS V INNER JOIN [FirstTreatments] AS T ON T.[MemberId] = V.[MemberId]
WHERE DATEDIFF(DAY, V.[VisitDate], T.[FirstTreatmentDate]) BETWEEN 0 AND 365
GROUP BY V.[MemberId], T.[FirstTreatmentDate]
This query should show the number of times a patient/member has visited the ER in the year before his/her first treatment date.
Here is a tester: https://rextester.com/UXIE4263

SQL Database Design for monthly issued coupons

I'm struggling with a database schema for a problem I'm having.
Let's say I own a business that sells monthly services (cleaning) to different companies.
However, I give companies monthly saveable 'coupons' that act like a reduction (of 5 dollars) based on their amount of users.
Example:
It's april 2018
Company XYZ has to pay 1.000 dollars for their monthly cleaning services by my business.
XYZ, has 5 employees, so they will have 5 coupons for the month of april.
HOWEVER, since coupons can be saved (for a period of 2 months), company XYZ will not use the coupons of only april, but also of march (since they didn't use any that month and february coupons are already used up).
Result:
10 coupons are used on their april invoice (5 of march, 5 of april):
total amount to pay 950 dollars
My thing is that I want to automate this. With one click on the button, my system will have to check:
How many users there are
If there are any unused coupons from last 2 months (and use those first if they exist)
Apply coupons to their invoice.
I want to design this first in a database but i'm struggling:
This is my design
Company
CompanyID
Name
User
UserID
CompanyID
UserID
Now I'm struggling with the coupon design, how can I develop this so that I can automise my problem.
I will need to save coupons per company per month.
My idea is to do it like this:
Company_Month_Coupon
CompanyID
Coupon_Count
Month
I wasn't sure if i could do this in one table and i'm not so sure with the following problem:
what if my program user decides to cancel an invoice, how would my system know from which month the coupons came?
What design would be adviced in a coupon-sharing system?
Any advice to tackling this problem would greatly appreciated.
I would go with your idea and have 2 more tables: Invoices and Invoices_UsedCoupons
Invoices:
ID (Primary key)
CompanyID
Month
Status (to set a cancelled status on your invoice if you don't want to delete from the DB)
Invoices_UsedCoupons:
InvoiceId (foreign key to Invoices table)
Coupon_Count
Month (this field is for the used coupons from Company_Month_Coupon table)
The reasons for this:
We should still store the issued coupons (in your Company_Month_Coupon table) because for each month, the number of employees may change. It means that you have to keep track of the issued coupons whenever the number of employees changes.
With Invoices and Invoices_UsedCoupons table, you could easily calculate the actual used coupons & the remaining coupons.
what if my program user decides to cancel an invoice, how would my
system know from which month the coupons came?
All the information is available in Invoices and Invoices_UsedCoupons tables. If you want to reclaim coupons after cancelling the invoice, it's also easy to do.
"I will need to save coupons per company per month."
Maybe you can do the opposite. In the database does not store coupons that can be used, but only those that are actually used, for example in the table "used_coupons"
The idea is that the coupons are given up by default, so it makes no sense to store them. Only need to save the used coupons.
At checkout you need to find out how much users is in the company and how many "used coupons" is saved in the last two months.
If X coupons are returned then from the "used_coupons" table you need to delete the latest X coupons.

Zoho Reports: SQL Query - Finding date and number of days

Problem Statement: I need to find out Over Due start date and from that i need to calculate number of Over due days. I know how to do for Over due days count, but i am not able to find a way to figure out for Over due start date.
Example: Let us say a customer did not pay for 4th November 2017, 4th December 2017, 4th Jan 2018, 4th Feb 2018. Now for these There were 4 Zero collection records placed in Collections table and 4 records placed in Over Due Collections table with D Flag. Now on 8th Feb Customer Paid an installment then the respective payment record has been placed in Collections table and another record in Over due collections with C flag. Since this payment gets adjusted for 4th November 2017 the Over due start date will be 4th December. Suppose if the customer did not pay then it will be 4th November 2017 as the Over due start date.
I have tables as follows for a Loan Management System:
Schedule (Payment Schedule): Which will have all the Installments, with the dates adn the respective amounts to be paid for each month.
Schema: LoanNo, Schedule Date, Installment No, Principle, Interest.
Collections (Payment Collections) for each month which has been collected. Suppose if the payment not received, A record placed with the respective date and with Zero amount. and another record will be placed in Over due collections table with D flag with the respective amounts. If there is any collection happens, then another record will be inserted with the flag C which represents collections.
Schema: LoanNo, PaymentReceived Date, Principle, Interest
Over Due Collections (Which there will be a record placed if there is a Due)
Schema: LoanID, Flag(D/C), Date, Principle, Interest
Please do suggest and guide me to write a proper query for this
it's interesting yet easy problem. you can tackle by calculating running sum of the amount and then compare with total payments by the customer. Take all the records having running sum greater than total payment. and choose minimum date out of it.
let me know if require further help I will give you SQL query. But you should try by your own
Edit 1
this will provide you running_sum
_______Subquery1_______
select a.LoanNO,a.Scheduledate,a.Amount,sum(b.amount)run_sum from
Paymentschedule a
join PayamentSchedule b
on a.LoanNo=b.LoanNo and a.ScheduleDate>b.ScheduleDate and
a.ScheduleDate<=now() group by 1,2,3
total collection against loan
_______subquery 2_____
select LoanNo,sum(amount)total collection from collection group by 1
now
select a.LoanNo,min(ScheduleDate) overduestartdate from subquery1 join subquery2 on
a.LoanNO=b.LoanNO
and a.run_sum>b.Collection group by 1
modify according to your schema

finding the first dates of items in a list using SQL

I'm building a local database in Access 2010 from reports of customer accounts that need demographic information searched. Each week a new report is generated and the results are added to the list, however there is duplication each week in the listing for those accounts that have not been found yet. I have been able to create queries that will display accounts that have only shown up on one report, and queries to display accounts that show up on multiple reports. But I am trying to now create a query that will show when an account was first added to the listing.
The columns I am looking at would be named similar to this:
accountNum - account number
custName - name of the customer
reportDate - the date that the account was pulled to be searched
The end result would be a table that shows all the accounts that (for example) appeared on multiple reports, but appeared first on December 1st, Dec 8th, Dec 15th, etc...
Thoughts?
This is an aggregation query:
select accountNum, custName, min(reportDate)
from reports
group by accountNum, custName;
This should get you a list of all of the accounts that appear multiple times along with the first date that they were reported.
SELECT
accountNum,
custName,
MIN(reportDate) AS firstReportDate
FROM
MyTable
GROUP BY
accountNum,
custName
HAVING
COUNT(*) > 1

SQL cohort query output

This is a sample query and I do not have the data associated with these values, but I just need to know what kind of chart/information would be the output of this request:
SELECT
cohorts.cohortyear,
YEAR(orders.time) AS purchaseyear,
SUM(orders.amount) AS amount
FROM orders,
(SELECT id AS customer_id, YEAR(created) AS cohortyear FROM customers) AS cohorts
WHERE orders.customer_id = cohorts.customer_id
GROUP BY cohortyear, purchaseyear;
Not sure I understand the question. By looking at the projections in the SELECT clause I am going to guess your output columns will look like:
cohortyear (integer) | purchaseyear (integer) | amount (some numeric)
The query would be better written and more intelligible if it used explicit join syntax:
SELECT co.cohortyear, YEAR(o.time) AS purchaseyear, SUM(o.amount) AS amount
FROM orders o join
(SELECT id AS customer_id, YEAR(created) AS cohortyear
FROM customers cu
) co
on o.customer_id = co.customer_id
GROUP BY co.cohortyear, purchaseyear;
It is taking customers and assigning them to similarity groups based on the year the customers record was created (assuming created does what it sounds like). So, all customers created in the same year are in the same group. Then, it calculates the amount spent in each year on or after that one. If you ran the query, the output would be pretty self explanatory. Something like:
CohortYear PurchaseYear Amount
2014 2014 $1000
2013 2014 $2000
2013 2013 $3000
. . .
The first row says that for customers who started in 2014, they spent $1000 in 2014. By contrast, customers who start in 2013 spent $2000 in 2014. And this group spent $3000 in 2013. However, the comparisons aren't very good, because it doesn't take into account the number of customers. But that is another matter.