I have a 2 tables, one with activity generated information, the other with new contract information. Ultimately what I'm trying to do is see if within 30 days after the activity date, a new contract was generated. So for example:
The first table is the activities table, the 2nd the contract table. As you'll see for example, account ABC123 does have a new contract within 30 days of the activity date - CT-7135. However, CT-7695, although it exists in the table and is associated with account ABC123, would not satisfaction the "New Contract" requirement b/c it started outside of the 30 window since the activity date.
Account GJ1234 however would be a "no" b/c there is no contract in the table that is within 30 days of the activity date. Likewise CGE435 (because of CT-4389) and GHE568 (because of contracts CT-4389, CT-8080 AND / OR CT-6690 ---- BUT NOT because of CT-6829) both qualify.
I guess my issue is trying to do this dynamic join off of activity date b/c it's different for each line items.
Thoughts?
Thanks.
Try this:
Select Distinct AccountId
From Accounts a
Where Exists
(Select * From contracts
Where AccountId = a.AccountId
And ContractDate >= a.ActivityDate
And DateDiff(day, a.ActivityDate, ContractDate) <= 30)
The following will find all the accounts that have had a new contract within 30 days of the activity:
SELECT * FROM activities AS A WHERE AccountID IN (SELECT DISTINCT(AccountID) from contracts WHERE ContractStartDate >= A.ActivityDate AND ContractStartDate <= DATE_ADD(A.ActivityDate, INTERVAL DAY 30))
Related
I have a sqlite3 database maintained on an AWS exchange that is regularly updated by a Python script. One of the things it tracks is when any team generates a new post for a given topic. The entries look something like this:
id
client
team
date
industry
city
895
acme industries
blueteam
2022-06-30
construction
springfield
I'm trying to create a table that shows me how many entries for construction occur each day. Right now, the entries with data populate, but they exclude dates with no entries. For example, if I search for just
SELECT date, count(id) as num_records
from mytable
WHERE industry = "construction"
group by date
order by date asc
I'll get results that looks like this:
date
num_records
2022-04-01
3
2022-04-04
1
How can I make sqlite output like this:
date
num_records
2022-04-02
3
2022-04-02
0
2022-04-03
0
2022-04-04
1
I'm trying to generate some graphs from this data and need to be able to include all dates for the target timeframe.
EDIT/UPDATE:
The table does not already include every date; it only includes dates relevant to an entry. If no team posts work on a day, the date column will jump from day 1 (e.g. 2022-04-01) to day 3 (2022-04-03).
Given that your "mytable" table contains all dates you need as an assumption, you can first select all of your dates, then apply a LEFT JOIN to your own query, and map all resulting NULL values for the "num_records" field to "0" using the COALESCE function.
WITH cte AS (
SELECT date,
COUNT(id) AS num_records
FROM mytable
WHERE industry = "construction"
GROUP BY date
ORDER BY date
)
SELECT dates.date,
COALESCE(cte.num_records, 0) AS num_records
FROM (SELECT date FROM mytable) dates
LEFT JOIN cte
ON dates.date = cte.date
There are 2 tables: TestService and TestPayment, related by ServiceID. The contents of these 2 tables are:
In all there are 3 services and 3 Fees. Each service has multiple payments associated with it; Service 1111 has 2 payments, Service 1112 has 3 payments and Service 1113 has 3 payments. Each payment has an associated DatePaid.
I want a query to show:
For each service, the sum of total payments received for that service, AND the date of the last payment made for that service
To do this I created 3 queries:
TestQPaymentByVHC#: This sums all the payments for each ServiceID
TestQLastInsPayment: This retrieves the date of the last payment for each ServiceID
TestQCPA: This should list all ServiceID’s (one record per ServiceID) with the sum of all payments received (From TestQPaymentByVHC#) and the date of the last payment received for each ServiceID (From TestQLastInsPayment)
Here is the problem:
If TestQLastInsPayment is:
SELECT TOP 1 TestPayment.ServiceID, Last(TestPayment.DatePaid) AS LastOfDatePaid, TestPayment.Amount
FROM TestPayment RIGHT JOIN TestService ON TestPayment.ServiceID = TestService.ServiceID
GROUP BY TestPayment.ServiceID, TestPayment.Amount
ORDER BY Last(TestPayment.DatePaid) DESC;
Then TestQCPA lists the date of the last payment for each ServiceID ONLY for ONE of the ServiceID’s:
If I change TestQLastInsPayment to:
SELECT TestPayment.ServiceID, Last(TestPayment.DatePaid) AS LastOfDatePaid, TestPayment.Amount
FROM TestPayment RIGHT JOIN TestService ON TestPayment.ServiceID = TestService.ServiceID
GROUP BY TestPayment.ServiceID, TestPayment.Amount
ORDER BY Last(TestPayment.DatePaid) DESC;
Then TestQCPA lists all dates of payment for each Service ID and each date a payment was received, and it duplicates records for each ServiceID such that each ServiceID is listed multiple times, one record for each date that a payment was received:
I am doing all this in the GUI and posting the SQL code.
How can I get TestQCPA to list ONLY one line per ServiceID, with the sum of all payments received for that ServiceID, but still have the DatePaid show the last date of payment for each ServiceID?
As I understand the request, the below query should provide the requested information. Max is used instead of last due to how access stores dates as seconds since 00:00:00 1/1/1900.
SELECT TestPayment.ServiceID, Max(TestPayment.DatePaid) AS MaxOfDatePaid, Sum(TestPayment.Amount) AS SumOfAmount
FROM TestPayment INNER JOIN TestService ON TestPayment.ServiceID = TestService.ServiceID
GROUP BY TestPayment.ServiceID
ORDER BY Max(TestPayment.DatePaid);
To include all the fields in your question:
SELECT svc.CPT, svc.Units, svc.Fee, svc.[Patient#], sum(pmt.amount) as [Sum of Amount Paid], max(pmt.datepaid) as [Date of Last Receipt], svc.serviceid
FROM testservice AS svc LEFT JOIN testpayment AS pmt ON svc.serviceid = pmt.serviceid
GROUP BY svc.serviceid, svc.CPT, svc.Units, svc.Fee, svc.[Patient#]
The LEFT JOIN is used because I assume that it is possible that TestService will contain a service for which no payments have yet been received and you said you want to see "for each service, the sum of total payments received for that service".
Thanks for all tips. Turns out problem was I was using LAST(DatePaid). Access does not seem to like LAST function with dates. When I changed to MAX(DatePaid) it all worked.
Eliminating duplicate answers and mismatch in SQL
So the problem states that I need to find the transactions that happened each day and there is a mismatch between my answer on the correct answer and I don't know why!
this is a Short database description "Recycling firm"
The firm owns several buy-back centers for the collection of recyclable materials. Each of them receives funds to be paid to the recyclables suppliers. Data on funds received are recorded in the table
Income_o(point, date, inc)
The primary key is (point, date), where the point holds the identifier of the buy-back center, and the date corresponds to the calendar date the funds were received. The date column doesn’t include the time part, thus, money (inc) arrives no more than once a day for each center. Information on payments to the recyclables suppliers is held in the table
Outcome_o(point, date, out)
In this table, the primary key (point, date) ensures each buy-back center reports about payments (out) no more than once a day, too.
For the case income and expenditure may occur more than once a day, another database schema with tables having a primary key consisting of the single column code is used:
Income(code, point, date, inc)
Outcome(code, point, date, out)
Here, the date column doesn’t include the time part, either.
and The question is :
Under the assumption that receipts of money (inc) and payouts (out) can be registered any number of times a day for each collection point [i.e. the code column is the primary key], display a table with one corresponding row for each operating date of each collection point.
Result set: point, date, total payout per day (out), total money intake per day (inc).
Missing values are considered to be NULL.
SELECT Income.point, Income."date", SUM("out"), SUM(inc)
FROM Income left JOIN
Outcome ON Income.point = Outcome.point AND
Income."date" = Outcome."date"
GROUP BY Income.point, Income."date"
UNION
SELECT Outcome.point, Outcome."date", SUM("out"), SUM(inc)
FROM Outcome left JOIN
Income ON Income.point = Outcome.point AND
Income."date" = Outcome."date"
GROUP BY Outcome.point, Outcome."date";
My guess is that you have a bit of a Cartesian join by not including CODE as part of your join criteria. I think the following query should suit your needs:
WITH calendar AS
(
SELECT TRUNC(SYSDATE)-(LEVEL-1) AS DT
FROM DUAL
CONNECT BY LEVEL < 30
)
SELECT d.pnt AS "POINT",
c.dt AS "DATE",
d.outcome_total,
d.income_total
FROM calendar c
LEFT JOIN (SELECT nvl(inc.pnt, outc.pnt) AS PNT,
nvl(inc.dt, outc.dt) AS DT,
outc.amt AS OUTCOME_TOTAL,
inc.amt AS INCOME_TOTAL
FROM (SELECT i.pnt, i.dt, sum(i.inc) AS AMT
FROM income i
GROUP BY i.pnt, i.dt) inc
FULL JOIN (SELECT o.pnt, o.dt, sum(o.inc) AS AMT
FROM outcome o
GROUP BY o.pnt, o.dt) outc ON inc.pnt = outc.pnt AND inc.dt = outc.dt) d ON c.dt = d.dt;
I added the calendar table to account for the case where there was neither an income nor an outcome on a given day. However, if you don't need that, the query within the LEFT JOIN should be just fine.
N.B.: With the addition of the calendar WITH clause, this query will currently only show results from the last month(-ish). If you need longer, adjust the 30 day window.
Thank you for taking the time to read this, it is probably a very basic question. Most search queries I did seemed a bit more in depth to the INNER JOIN operator.
Basically my question is this: I have a shipping and receiving table with dates on when the item was either shipped or received. In the shipping table (tbl_shipping) the date row is labeled as trans_out_date and for the receiving table (tbl_receiving) the date row is labeled as trans_in_date.
I can view transactions set on either table from a user entered form but I want to populate a table with information pulled from both tables where the criteria meets. ie. If the receiving table has 10 transactions done in April and 5 in June and the shipping table has 15 transactions in April and 10 in June... when the user wants to see all transactions in June, it will populate the 15 transactions that occurred in June.
As of right now, I can pull only from 1 table with
SELECT *
FROM tbl_shipping
WHERE trans_out_date >= ‘from_date’
AND trans_out_date <= ‘to_date’
Would this be the appropriate syntax for what I am looking to achieve?
SELECT *
FROM tbl_shipping
INNER JOIN tbl_receiving ON tbl_shipping.trans_out_date = tbl_receiving.trans_in_date
WHERE
tbl_shipping.trans_out_date >= ‘from_date’
AND tbl_shipping.trans_out_date <= ‘to_date’
Thank you again in advance for reading this.
You appear to want union all rather than a join:
SELECT s.item, s.trans_out_date as dte, 'shipped' as which
FROM tbl_shipping S
WHERE s.trans_out_date >= ? AND
s.trans_out_date <= ?
UNION ALL
SELECT r.item, NULL, r.trans_in_date as dte, 'received'
FROM tbl_receiving r
WHERE r.trans_out_date >= ? AND
r.trans_out_date <= ?
ORDER BY dte;
Notes:
A JOIN can cause problems due to data that goes missing (because dates don't line up) or data that gets duplicated (because there are multiple dates).
The ? is for a parameter. If you are calling this from an application, use parameters!
You can include additional columns for more information in the result set.
This may not be the exact result format you want. If not, ask another question with sample data and desired results.
I'm trying to develop a query that will show the historical backlog, month by month for applications my organization processes.
The table I'm querying has each row represent an application.
This is fairly simple for a single month by taking into account when the application was created and when it was closed. I can use the code below.
SELECT COUNT(*)
FROM APPLICATIONS
WHERE TRUNC(CRTE_DTE,'mm') <= TO_DATE('09/01/2016','mm/dd/yyyy')
AND (TRUNC(CLOS_DTE,'mm')> TO_DATE('09/01/2016','mm/dd/yyyy') OR CLOS_DTE IS
NULL)
;
What I would like to do, is create something like this but grouped by month.
i.e. with output that looks similar to:
January 250
February 350
March 290
etc.
For my purposes, I'm defining backlog as any application that hadn't yet been closed by the time that month had ended while excluding any applications opened after that month had ended.
I don't have access to run PL/SQL, but if that's a requirement please let me know.
First time posting here, so if I didn't explain something correctly, let me know!
Try something like this:
SELECT d.dt, COUNT(*)
FROM
APPLICATIONS a,
(SELECT ADD_MONTHS(:DATE1, ROWNUM-1) DT FROM DUAL CONNECT BY ROWNUM<=MONTHS_BETWEEN(:DATE2, :DATE1)+1) d
WHERE TRUNC(a.CRTE_DTE,'mm') <= d.dt
AND (TRUNC(a.CLOS_DTE,'mm')> d.dt OR CLOS_DTE IS NULL)
GROUP BY D.DT
:date1 - start date, for example 08/01/2016, :date2 - end date, for example 10/01/2016, in subquery we get row for each month between :date1 and :date2, and then count backlog for them.