MySQL Distinct (Unique) values over time - php

I have a question about constructing a MySQL query. I have a table with one column containing values, and another column containing timestamps. What I'd like to do is get the number of distinct (unique) values for a field from a specific epoch up until various points in time so that I can plot the number of unique values over time. For example, I'd like the query result to look like the following:
Date, COUNT( DISTINCT col1)
2011-02-01, 10
2011-02-02, 16
2011-02-03, 24
etc.
Note that these values are the number of distinct values starting the same point in time. Currently to accomplish this, I'm using a loop in PHP to iterate a single query for each date and it takes forever since I have a large DB. To give a better picture, the inefficient code I'd like to replace looks like the following:
for($i=0;$i<count($dates),$i++){
$qry = "SELECT COUNT (DISTINCT `col1`) FROM `db`.`table` WHERE `Date` BETWEEN '".$EPOCH."' AND '".$dates[$i]."';";
}
Any help would be appreciated.
Thanks

If understood your question, you can use a GROUP statement:
SELECT StampCol, COUNT(DISTINCT DataCol) FROM MyTable GROUP BY StampCol

SELECT DATE_FORMAT(date_column, "%Y-%m-%d") AS date_column, COUNT(visitors) AS visitors FROM table GROUP BY DATE_FORMAT(date_column, "%Y-%m-%d") ORDER BY date_column desc"

Related

SQL PHP get full row with MAX i a single table

i have one table collecting scores and other informations like the date and the user id. I would like to get the MAX of the current month and the other fields of the row. I'm having a problem to get the other informations since with functions we cannot get other fields.
I think i should do an inner join but i don't how to make it.
Thank you.
Your question is rather vague. But if you want one row, then the idea for the solution is order by and fetch first row only.
In standard SQL, the query would look like:
select t.*
from t
where extract(year from datecol) = extract(year from current_date) and
extract(month from datecol) = extract(month from current_date)
order by t.score desc
fetch first 1 row only;
Databases often differ on database functions. For instance, many use year() and month() functions, rather than extract(). Similarly, many databases do not support fetch first 1 row only, using limit or select top instead.
Thank you, yes it does work doing this way but the idea was to use MAX (for learning purpose).
I have scores table, with the following fields: id, score, date, user_id
I would like, using MAX, to get the best and latest score of the current month along with the other fields (ie the id, date and user_id).

Parse SQL results by month using timestamp MySQL

I have a small problem with SQL. I need to select ID of rows and group them into arrays (or something) BY MONTH? I have a timestamp column there.
So if there are rows like this:
ID Timestamp
1 blalba(1.10.2017)
2 blabla(2.10.2017)
3 blabla(1.5.1996)
The output would be like
array(
[5.1996] => array([3]),
[10.2017] => array([1,2]);
)
(Or something like this).
Is this possible in PHP using some PHP libraries? Or Do I have to implement my own class doing this?
You are probably looking for group_concat
select group_concat(id separator ', ') as myList,
DATE_FORMAT(Timestamp, '%Y-%m') from <YOUR_TABLE>
GROUP BY DATE_FORMAT(Timestamp, '%Y-%m');
Well you might be handle this on the MySQL side by ordering by month/year:
SELECT
ID, Timestamp
FROM yourTable
ORDER BY
DATE_FORMAT(Timestamp, '%Y-%m');
This query would return a result set to PHP which would be ordered such that all records in the same month and year would be clustered together. You could then just iterate this result set and process the records as you want.

MySQL select first five unique rows depending on two columns

I have a mysql table which have two columns for selecting propouses - tablica and contentid as it shows here
i want to select first five rows sorted by date DESC which have unique combination of both columns - tablica and contentid
how that can happend? I've tried already with combinations of distinct, group_concat and concat but everything i've tried skip some of the rows.
please help.
Hello_ mate
If you don't need other stuff than those two fields you can use the query I did post in the comments below your question.
Otherwise if you need all the fields you can use this query:
SELECT `id`, `tablica`, `contentid`, `ip`, `userid`, MAX(date) as `date`
FROM test2
GROUP BY tablica, contentid
ORDER BY date DESC
LIMIT 5;
using the MAX function we select the latest matching date for this tablica and contentid, if you want to get oldest date use MIN function
Let me know if this works for you.
Good Luck!

Get unique values of SQL table and echo with PHP

I have a MySQL table with over 200 values. One of the columns on my table is 'date'. Out of all 200 values there are only 5 unique dates.
How can I list out the unique values of the dates and echo them with php. e.g. not getting back 200 instances of dates but just 5.
Use DISTINCT
SELECT DISTINCT `date` FROM `tablename`....
SELECT myDate FROM myTable GROUP BY myDate
Or...
SELECT DISTINCT myDate FROM myTable
DISTINCT is a nice short hand, but if you ever then want to make use of the query for other purposes, if often constrains you a bit too much. So I prefer the GROUP BY version.

Join two tables, then Order By date, BUT combining both tables

Alright, I'm trying to figure out why I can't understand how to do this well...
I have two tables:
invoices:
id
userID
amount
date
payments:
id
userID
amount
date
So, the goal here is to join both tables, where the userID matches whatever I want it to be - and then return everything ordered by date (most recent at the top). However, because there is a date field in each of the tables, I'm not sure how MySQL will handle things... will is sort by both dates automatically? Here's what I was thinking...
"SELECT DISTINCT *
FROM invoices,payments
WHERE {$userID} = invoice.userID
OR {$userID} = payments.userID
ORDER BY date DESC";
But, it's starting to become clear to me that maybe this isn't even the right use of a join command... maybe I need to just get all data on each table alone, then try to sort it somehow with PHP? If that's the better method, what's a good way to do this type of DATE sort while keeping all row data in tact?
I should add, the TIME inside the unix timestamp (that's how "date" is stored) is NOT negligible - it should sort by the date and time.
Thanks all...
If the columns of both tables are the same, you can use a UNION
SELECT X.*
FROM ( SELECT `id`,
`userID`,
'INVOICE' AS PTYPE
`amount`,
`date`
FROM `invoices`
WHERE {$userID} = userID
UNION
SELECT `id`,
`userID`,
'PAYMENT' AS PTYPE
`amount`,
`date`
FROM `payments`
WHERE {$userID} = userID
) X
ORDER BY X.`date`
EDIT
Read the relevant section of the MySQL manual on UNIONS. There are other ways of phrasing this, but this is my preferred style - it should be clear to anybody reading that the ORDER BY clause applies to the result of both sides of the UNION. A carelessly written UNION - even with an ORDER BY - may still leave the final resultset in indeterminate order.
The purpose of the PTYPE is that this query returns an extra column called PTYPE, that indicates whether each individual row is an INVOICE or a PAYMENT... ie. which of the two tables it comes from. It's not mandatory, but can often be useful within a union
Because you have two identical fields named date, MySQL will not know which one you're trying to order by.
"SELECT DISTINCT *
FROM invoices,payments
WHERE {$userID} = invoice.userID
OR {$userID} = payments.userID
ORDER BY invoices.date, payments.date DESC";
This would sort on the invoice date, then the payment date - if that's what you are trying to find out
If your data tipe is Date, Timestamp, or anything related, the SGBD will order it properly. If that was what you've asked.
But if the datatype is String, even when dates is store, it will not sort the way you want.

Categories