Get Last Column in Each Different Customer ID - mysql

I have a table with Invoice Date and Customer ID (among other data, of course). I'm looking to display the longest invoice date in the future in the table for each customer.
I am currently using this MySQL in the WHERE:
WHERE o70vm_invoices_invoices.invoice_date = (SELECT MAX(o70vm_invoices_invoices.invoice_date) FROM o70vm_invoices_invoices)";
This code currently displays the oldest date in the column for just one customer.
I'm including my entire MySQL query below, please keep in mind that I'm having to pull from various tables to display the data I need.
$query = "SELECT
o70vm_invoices_contacts.name AS 'Parent_Name',
o70vm_invoices_contacts.id AS 'Parent_ID',
o70vm_invoices_contacts.company AS 'Children',
o70vm_invoices_contacts.active AS 'Active',
o70vm_invoices_invoices.id AS 'Invoice_ID',
o70vm_invoices_invoices.user_id AS 'Parent_ID_on_Invoice',
o70vm_invoices_invoices.invoice_num AS 'Invoice_Num',
o70vm_invoices_invoices.invoice_date AS 'Invoice_Date',
o70vm_invoices_invoices.invoice_duedate AS 'Invoice_Date_Due',
o70vm_invoices_payments.invoice_id,
o70vm_invoices_payments.id,
o70vm_invoices_payments.payment_amount AS 'Payment_Amount',
o70vm_invoices_payments.payment_datetime AS 'Payment_Date',
o70vm_invoices_payments.payment_duedate,
o70vm_invoices_payments.payment_status AS 'Payment_Status',
o70vm_invoices_payments.payment_description AS 'Payment_Descript',
o70vm_invoices_payments.payment_type AS 'Payment_Type'
FROM o70vm_invoices_invoices, o70vm_invoices_contacts, o70vm_invoices_payments
WHERE
o70vm_invoices_contacts.id = o70vm_invoices_invoices.user_id
AND
o70vm_invoices_payments.invoice_id = o70vm_invoices_invoices.id
AND
o70vm_invoices_invoices.invoice_date < '2099-01-01'
AND
o70vm_invoices_contacts.active = 1
AND o70vm_invoices_invoices.invoice_date = (SELECT MAX(o70vm_invoices_invoices.invoice_date) FROM o70vm_invoices_invoices)";
If I use a GROUP BY:
GROUP BY o70vm_invoices_contacts.id
I can pull each customer to display but it does not display the last future invoice in the table.
Based on Stefan's comments below, here is my revised subquery:
$query = "SELECT *
FROM ( SELECT
o70vm_invoices_contacts.name AS 'Parent_Name',
o70vm_invoices_contacts.id AS 'Parent_ID',
o70vm_invoices_contacts.company AS 'Children',
o70vm_invoices_contacts.active AS 'Active',
o70vm_invoices_invoices.id AS 'Invoice_ID2',
o70vm_invoices_invoices.user_id AS 'Parent_ID_on_Invoice',
o70vm_invoices_invoices.invoice_num AS 'Invoice_Num',
o70vm_invoices_invoices.invoice_date AS 'Invoice_Date',
o70vm_invoices_invoices.invoice_duedate AS 'Invoice_Date_Due',
o70vm_invoices_payments.invoice_id,
o70vm_invoices_payments.id,
o70vm_invoices_payments.payment_amount AS 'Payment_Amount',
o70vm_invoices_payments.payment_datetime AS 'Payment_Date',
o70vm_invoices_payments.payment_duedate,
o70vm_invoices_payments.payment_status AS 'Payment_Status',
o70vm_invoices_payments.payment_description AS 'Payment_Descript',
o70vm_invoices_payments.payment_type AS 'Payment_Type'
FROM o70vm_invoices_invoices, o70vm_invoices_contacts, o70vm_invoices_payments
WHERE
o70vm_invoices_contacts.id = o70vm_invoices_invoices.user_id
AND
o70vm_invoices_payments.invoice_id = o70vm_invoices_invoices.id
AND
o70vm_invoices_invoices.invoice_date < '2099-01-01'
AND
o70vm_invoices_contacts.active = 1
ORDER BY o70vm_invoices_invoices.invoice_date DESC
) AS tmp
GROUP BY tmp.id";
This query lists the first invoice date and not the last invoice date. If I change the order to ASC, it just sorts the results of the first invoice date.
Any help, much appreciated.

Best way might be to make use of a sub query:
SELECT *
FROM (
SELECT *
FROM o70vm_invoices_invoices
ORDER BY invoice_date DESC
) AS tmp
GROUP BY tmp.id

I'm sure there is a better way to do this; however, this works.
I just added MAX inside my query as such:
max(o70vm_invoices_invoices.invoice_date) AS 'Invoice_Date',
and this lists the furthest date for each customer.

Related

Retrieve more than 1 mysql column using AND statement

I am using mysql and what I am tryng to achieve, is to select more than 1 column in a select statement. From the sample code I have posted, I can retrieve the value 'Box Retrieval' in the activity column. However, what I would like to do, is select the values, 'Box Retrieval' 'Box Return, etc, Is this possible. Thanks
$query = "SELECT * FROM act WHERE company = '".$_SESSION['kt_idcode_usr']."' AND activity = 'Box Retrieval' ORDER BY date DESC";
Try this might be helpful for you.
$query = "SELECT * FROM act WHERE activity IN ('Box Return', 'Box Retrieval', 'Box Destruction') AND company = '".$_SESSION['kt_idcode_usr']."' ORDER BY date DESC";
You can just add another condition with OR statement having the value you need -
$query = "SELECT * FROM act WHERE company = '".$_SESSION['kt_idcode_usr']."' AND activity = 'Box Retrieval' OR activity = 'Box Return' ORDER BY date DESC";
This will return all rows which have activity value either 'Box Retrieval' or 'Box Return'
You can repeat for more such cases.
Or you can use UNION of two SQL SELECT statements but I think OR should suffice in this case.

Select only distinct values for a particular column mysql

We have two tables in mysql database.Screenshots are attached below.
Given table ads_testTable
here is the screenshot of my dimesnionvalue_flattable
We have to run a query like the one below.
SELECT Quiz_Attempt.L1_Key dimID,
Quiz_Attempt.L1_Label CatVars,
COALESCE(**xyz**,0) AS series0
FROM DSQ_ADSSCHEMA.ADS_TestTable dataTable
RIGHT OUTER JOIN LS_CONFIG.DSQ_DIMENSIONVALUES_FLAT Quiz_Attempt on dataTable.Quiz_Attempt = Quiz_Attempt.L1_Key
WHERE Quiz_Attempt.L0_Key = 'All Levels' AND
Quiz_Attempt.DimensionID = 'Packet'
GROUP BY Quiz_Attempt.L1_Key, Quiz_Attempt.L1_Label;
My motive is to write a query in place of xyz so that I can get avg of obtainedMarks column in testtable according to the value of dimID I get.Each distinct Quiz_Attempt is a different test so If a Packet is repeating for a particular Quiz_Attempt in testTable, it should take only one value for that AttemptID.
I think you query could take the form of:
SELECT
L1_Key dimID,
L1_Label CatVars,
COALESCE('**xyz**',0) AS series0
FROM (
SELECT *
FROM (SELECT * FROM ADS_TestTable GROUP BY ADS_TestTable.Quiz_Attempt) dataTable
RIGHT OUTER JOIN DSQ_DIMENSIONVALUES_FLAT Quiz_Attempt on dataTable.Quiz_Attempt = Quiz_Attempt.L1_Key
WHERE Quiz_Attempt.L0_Key = 'All Levels' AND
Quiz_Attempt.DimensionID = 'Packet'
GROUP BY dataTable.Quiz_Attempt
) A GROUP BY dimID, CatVars;
The JOIN is done in an inner query, and grouped by Quiz_Attempt, so that you get a single row per attempt. This result is then used to compute what you need.

How to make a 1 column query by choosing from two columns mysql

I have a messaging system (very basic) that has a table like this:
**MESSAGE_ID** **RUSER_ID** **SUSER_ID** **MESSAGE_DATA** **DATE**
RUSER is the receiving user, and SUSER is the sending user. If I wanted to output a query that would output a certain users messages, I would currently do:
Select * from PRIVATE_MESG where RUSER_ID=$USER_ID or SUSER_ID=$USER_ID
That would give me all message_id's that are associated with that USER_ID. What I would like, is to create a column that would produce only the ID associated with RUSER_ID or SUSER_ID associated with a specific user. I need it to choose the messages that RUSER_ID or SUSER_ID are equal to a USER_ID but only display the one that isn't USER_ID
I would then like to do a group by the output of that query.
Any help is greatly appreciated!
Thanks!
update I am not really looking for a message_id, I am just looking for a list of users who that person has written to or received from.
UPDATE
Just so everyone knows, I recieved the answer to this question perfectly! I tweaked it later on so that it would also display them by date from newest to oldest. I did this by spliting the DATETIME into DATE and TIME USING the DATE() and TIME() Function. Here was my final query:
SELECT
IF(RUSER_ID = $USER, SUSER_ID, RUSER_ID) as THE_OTHER_GUY, DATE(DATE) as DAY, TIME(DATE) as TIME
FROM PRIVATE_MESG
WHERE RUSER_ID = $USER
OR SUSER_ID = $USER;
group by THE_OTHER_GUY ORDER BY DAY DESC, TIME DESC
Hope this helps the next person!
You can query:
SELECT
*,
IF(RUSER_ID = $USER_ID, SUSER_ID, RUSER_ID) as THE_OTHER_GUY
FROM PRIVATE_MESG
WHERE RUSER_ID = $USER_ID
OR SUSER_ID = $USER_ID;
SELECT SUSER_ID FROM PRIVATE_MESG WHERE RUSER_ID=$USER_ID
UNION
SELECT RUSER_ID FROM PRIVATE_MESG WHERE SUSER_ID=$USER_ID
It retrieves:
- the list of user IDs who sent messages to $USER_ID
- the list of user IDs who received messages from $USER_ID
And UNION groups the 2 lists in a single result set.

Counting the number min records within groups

I'm building a report for a database where I need to determine the number of "first scans" grouping by company, job, and date.
The scan table can contain multiple scans for the same item, however I only want to include the original scan in my COUNT, which can only be identified as being the scan with the earliest date that matches a particular item.
My first attempt at this was:
SELECT
_item_detail.job_id,
_item_group.group_id,
_scan.company_id,
DATE(scan_date_time) as scan_date,
COUNT(1)
FROM _scan
INNER JOIN _item_detail ON _item_detail.company_id = _scan.company_id
AND
_item_detail.serial_number = _scan.serial_number
INNER JOIN _item_group ON _item_group.group_id = _item_detail.group_id
WHERE _item_detail.job_id = '0326FCM' AND _scan.company_id = '152345' AND _item_group.group_id = 13
GROUP BY
_item_detail.job_id,
_item_group.group_id,
_scan.company_id, scan_date -- first_scan_count
HAVING min(scan_date_time);
This is giving me incorrect results, though (about 3x too many). I am assuming it's because the MIN record is being recalculated for each date, so if the min was found on day 1, it may also be found on day 3 and counted again.
How can I modify my query to achieve the desired results?
Something similar to this should work... I'm not completely sure of how your tables are laid out or how the data relates them together, but this is the general idea:
SELECT
_item_detail.job_id,
_item_group.group_id,
_scan.company_id,
DATE(scan_date_time) as scan_date,
COUNT(1)
FROM
_scan s1
INNER JOIN _item_detail
ON _item_detail.company_id = s1.company_id
AND _item_detail.serial_number = s1.serial_number
AND _item_detail.job_id = '0326FCM'
INNER JOIN _item_group
ON _item_group.group_id = _item_detail.group_id
AND _item_group.group_id = 13
WHERE
s1.company_id = '152345'
AND s1.scan_date_time = (
SELECT MIN(s2.scan_date_time)
FROM _scan s2
WHERE
s2.company_id = s1.company_id
AND s2.serial_number = s1.serial_number
)
GROUP BY
_item_detail.job_id,
_item_group.group_id,
s1.company_id
I don't quite follow your query, but based on the description of the problem, I'd say create a subquery that gives the min scan date for for each item, group by items, the perform your outer select on that.

Converting a SQL query with group by into LINQ query

I'm stuggling to replicate a SQL query into LINQ.
Can any one help?
SQL:
SELECT tblInvoice.lngID AS InvoiceID,
tblInvoice.dtTimeStamp AS InvoiceDate,
tblInvoice.strReference,
tblInvoice.fltTotalValue,
max(Project.ProjectID) AS ProjectID,
max(Project.ProjectName) AS ProjectName,
max(Project.Location) AS ProjectLocation
FROM tblInvoice INNER JOIN
tblInvoiceLine ON tblInvoice.lngID = tblInvoiceLine.lngInvoiceID
WHERE (tblInvoice.intStatus != 0)
AND (tblInvoice.lngPersonID = #PersonID)
GROUP BY tblInvoice.lngID, tblInvoice.dtTimeStamp, strReference, fltTotalValue
ORDER BY tblInvoice.lngID DESC
LINQ so far:
var invoices = from inv in db.TblInvoices
join invLine in db.TblInvoiceLines on inv.LngID equals invLine.LngInvoiceID
where inv.IntStatus != 0
where inv.LngPersonID == personID
group inv by new {inv.LngID,inv.DtTimeStamp,inv.StrReference,inv.FltTotalValue} into newInv
Part of the problem is that I want to do a
select new Invoice(){
}
and build up my custom Invoice object but, I cant see any of the properties in newInv.
Can any one advise?
I don't have time for a full answer now, but:
To get at properties of the key, use newInv.Key.StrReference etc
To get at aggregates (e.g. max values) use newInv.Max(x => x.ProjectId) etc
Hopefully that'll be enough to get you going. Basically, newInv will be a group of entries, with an associated key (which is what you grouped by).