How to Select MAX Date, and then find sum after that date - sql

SUM is not giving correct amount when WHERE condition is NULL
SELECT
DE."Donor First Name",
DE."Donor Last Name",
EX."SUM(Amount)",
No."MAX(Note Written)",
SUM(DE."Amount")
FROM "Latest Thank You Note" AS No
JOIN "Over 250 - Donors List" AS EX ON No."Full Name" = EX."Donor Name"
JOIN "Donor Table" AS DE ON No."Full name" = DE."Full Name"
WHERE DE."Date" >= No."MAX(Note Written)"
OR No."Max(Note Written)" Is NULL
GROUP BY 1,
2,
3,
4
Here is the code I am writing. It pulls donors names, their total amount donated, then the last time they were written a thank you note, and what they've donated since. However, sometimes when I pull this table, if there was never a thank you note written "MAX(Note Written") is Null, then it will give me a random sum. Is there any way to fix it?
I Tried removing the null but it doesn't pull the correct results.

Related

Access - return field based on criteria for a different field

I currently have a query that tells me the date of someone's last donation:
Max(Donations.DonationDate) AS MaxDate
I want to know the amount of that donation (Donations.DonationAmount).
I can get my query to show amounts for all donations, or I can get it to show me the amount of the maximum donation, but I don't know how to get it to show me the amount of the donation associated with MaxDate.
I'm not what terms to search for - I think I want something that will basically say "for MaxDate, return DonationAmount," but I'm not sure how to say that in SQL.
Image of two rows of test data
If someone gave $500 on 2/2/2020 and $100 on 3/5/2020, I want to see their last donation (MaxDate). The code below correctly returns 3/5. But then I also want to see the amount of that donation on 3/5/2020 ($100).
I've figured out how to see all the amounts ($500 and $100) and how to see the maximum amount ($500), but I don't know how to figure out the value for the MaxDate's amount.
The full code:
SELECT Nz(ContactHouseholds.HouseholdName, "ACCT:" & Donations.AccountName & " CONTACT:" & Donations.ContactName) AS HsName
,Max(Donations.DonationDate) AS MaxDate
,Households.HouseholdAddressEtc
FROM (
Donations LEFT JOIN ContactHouseholds ON Donations.ContactName = ContactHouseholds.ContactName
)
INNER JOIN Households ON Donations.HouseholdName = Households.HouseholdName
GROUP BY Nz(ContactHouseholds.HouseholdName, "ACCT:" & Donations.AccountName & " CONTACT:" & Donations.ContactName)
,Households.HouseholdAddressEtc

Consistent error of Alias Name cannot match another table/alias name in FROM clause

I am new to SQL and programming in general and am writing to write a data pull which would pull the monetary value for the category as well as department for each observation that we have. Yet I encounter this error. Any help is really appreciated.
SELECT CAST(ROUND(sales.store_nbr,0) AS INT) AS "Store NUMBER", dept.acct_dept_nbr AS "Department NUMBER", dept.dept_desc AS "Department Description", SUM(sales.wkly_sales) AS "Weekly sales",SUM(sales.yrly_sales) AS "Yearly Sales"
--pull sales and quantity by store
FROM CA_WM_VM.SKU_DLY_POS sales, CA_WM_VM.DEPT_DESC dept, ca_wm_vm.item item, CA_WM_VM_SKU_YRLY_POS sales
--for a store, for a period of time
WHERE sales.item_nbr = item.item_nbr
AND item.dept_nbr = dept.acct_dept_nbr
AND sales.wm_yr_wk BETWEEN 11613 AND 11713
--group by store number, & dept number
GROUP BY sales.store_nbr, dept.acct_dept_nbr, dept.dept_desc
The first and last table in the from clause have the same alias name "sales".

How to count a total in Postgresql and not have a range for each row?

On our postgreSql Database we have two table one is appointment and the other one location. We are currently counting the number of Appointment per location.
We use the following query. Unfortunately it is giving one row per every appointment whereas we would like to count the total. Is there a way to do this?
Thank you!
select "domain".locations."name" AS "Location Name",
COUNT("domain".appointments."id") AS "Number Of Appointment",
"domain".locations.mongo AS "Location ID Mongo",
"domain".locations."id" AS "Location ID",
"domain".countries."name" AS "Country Name",
to_char("domain".appointments.created_at,'FMDD.MM.YYYY') AS "Appointment Created Date"
from "domain".appointments
INNER JOIN "domain".locations
ON "domain".locations."id" = "domain".appointments.location_id
INNER JOIN "domain".countries
ON "domain".locations.country_id = "domain".countries."id"
WHERE "domain".appointments."source" = 'extranet'
AND date_trunc('day', "domain".appointments.created_at) = date_trunc('day', current_date - 1)
AND "domain".locations."id" <> '2016'
GROUP BY "domain".locations."id",
"domain".locations."name",
"domain".countries."name",
"domain".appointments.created_at,
"domain".appointments."id"

Select Max Row from Column

I have scan codes used in a table, but the table doesn't save just the newest scan codes. So I have order numbers with multiple items on those orders.
The issue is I need the last scan code on each item number for each order and not every time it has been scanned. Essentially I don't need to know that it has been scanned from prep to customization to shipping. I just need to know that it is in shipping. I get three results for one item number because it has been scanned three times.I don't need duplicate result from where it has been previously scanned.
The "S3DTNSEQ#" column is the number of times it has been scanned.I need to only keep the rows with the highest scan count. Anything lower than the highest scan count I need to get rid of. The 'Scan To' column is "S3DTSTO". So using the "S3DTNSEQ#" column to determine which row is kept is the idea.
SELECT
TMON as "order number",
TMCPO# as "po#",
TMRQD as "due date",
S3ITNO as "item number",
S3ORQT as "quantity",
TMCUST as "cust#",
TMNAME as, "cust name"
S3DTSTO as "scanned to",
TMSCHID as "sched id,
MAX( S3DTNSEQ# ) AS "S3DTNSEQ#",
S3DTADT as "maintained date"
FROM
TSA400.NRPDTA.SOP114F1 SOP114F1,
TSA400.NRPDTA.SOA SOA,
TSA400.NRPDTA.S3O S3O,
TSA400.NRPDTA.S3DTU S3DTU
WHERE SOP114F1.TMON = SOA.SOON
AND SOP114F1.TMSHP# = SOA.SOSHPN
AND SOP114F1.TMCUST = SOA.SOCUST
AND SOA.SOON = S3O.S3ON
AND SOP114F1.TMON = S3O.S3ON
AND SOA.SOCUST = S3O.S3CUST
AND SOP114F1.TMCUST = S3O.S3CUST
AND SOA.SOSHPN = S3O.S3SHPN
AND SOP114F1.TMON = S3DTU.S3DTON
AND SOP114F1.TMSHP# = S3DTU.S3DTSHP#
GROUP BY
TMON,
TMCPO#,
TMRQD,
S3ITNO,
S3ORQT,
TMCUST,
TMNAME,
S3DTSTO,
TMSCHID,
S3DTADT
I imagine I need a subquery to do this, but i am completely lost, on how to do this. I apologize, the query was created in "Showcase" which uses where clauses extensively instead of joins.

SQL join without duplicates

I need to return a single line per "WO #" (VIEW_SPS_WO_OPERATION. SI_NUMBER as "WO #")
The fields being returned show the same values in more than one row so my join might not be correct
Except for the following: one single “WO #” can have more than one NEXT_DELIVERY_DATE from
“VIEW_WOBOM.NEXT_DELIVERY_DATE”, I only need the entry with latest date (max?).
I hope I’m being clear.
Thanks in advance for your help.
SELECT
VIEW_SPS_WO_OPERATION.COMPANY_NAME as Customer,
VIEW_SPS_WO_OPERATION. SI_NUMBER as "WO #",
VIEW_SPS_WO_OPERATION. PN as "Part Number",
VIEW_SPS_WO_OPERATION. DEPT_NAME as "Department",
VIEW_SPS_WO_OPERATION. TOTAL_PARTS as "Extended Price",
VIEW_SPS_WO_OPERATION.DESCRIPTION as Description,
VIEW_WO_SUB.WORK_TYPE as "Work Req.",
VIEW_SPS_WO_OPERATION.STATUS_DESC as Task,
VIEW_SPS_WO_OPERATION.ENTRY_DATE as "Rec Date",
VIEW_SPS_WO_OPERATION.DUE_DATE as "Qtd Date",
VIEW_SPS_WO_OPERATION.EST_COMP_DATE as "App. Date",
VIEW_WO_TASK_STATISTICS.SKILLS_EST_HOURS as "Est. Labor Hrs.",
VIEW_WO_TASK_STATISTICS.LABOR_HOURS as "Act. Labor Hrs.",
VIEW_WOBOM.NEXT_DELIVERY_DATE
FROM
GATCRGQCTL.VIEW_SPS_WO_OPERATION VIEW_SPS_WO_OPERATION,
GATCRGQCTL.VIEW_WO_SUB VIEW_WO_SUB,
GATCRGQCTL.VIEW_WO_TASK_STATISTICS VIEW_WO_TASK_STATISTICS,
GATCRGQCTL.VIEW_WIP_VALUATION VIEW_WIP_VALUATION,
GATCRGQCTL.WO_BOM WO_BOM,
GATCRGQCTL.VIEW_WOBOM VIEW_WOBOM
WHERE
VIEW_SPS_WO_OPERATION.SI_NUMBER = VIEW_WO_SUB. SI_NUMBER
AND
VIEW_WIP_VALUATION.WOO_AUTO_KEY = WO_BOM. WOO_AUTO_KEY AND
VIEW_SPS_WO_OPERATION.WOO_AUTO_KEY = VIEW_WIP_VALUATION.WOO_AUTO_KEY AND
WO_BOM.WOT_AUTO_KEY = VIEW_WO_TASK_STATISTICS.WOT_AUTO_KEY
AND
WO_BOM.WOT_AUTO_KEY = VIEW_WOBOM.WOT_AUTO_KEY
You need the MIN(VIEW_WOBOM.NEXT_DELIVERY_DATE) and in your WHERE clause you need to limit the results to those where VIEW_WOBOM.NEXT_DELIVERY_DATE >= Now().
How you calcualte NOW will depend on your RDBMS.