find unique items based on date column - mysql

I need to find unique items based on date column. I tried to group the data together, but am not getting the desired result.
In the below sample i need to find the new entry i.e."New Company" seen on date 27th July because it does not exists on 16th July. I have thousand such rows and various dates.
The table contains issues seen on an Operating system datewise. I need to find the new issues a particular company is hitting. Pls help!
mysql> select * from testdata;
+------------+----------------+-----------------------+
| date | os_ver | account_name | count |
+------------+----------------+-----------------------+
| 2018-07-16 | 22.345-595 | Company AA1 | 2 |
| 2018-07-16 | 22.346-596 | Company BB1 | 1 |
| 2018-07-16 | 22.346-596 | Company CC1 | 2 |
| 2018-07-27 | 22.346-595 | Company AA1 | 1 |
| 2018-07-27 | 22.346-596 | Company BB1 | 2 |
| 2018-07-27 | 22.346-596 | New Company | 1 |
| 2018-07-27 | 22.346-596 | Company CC1 | 1 |
+------------+----------------+----------------------
I tried the below, but it's not showing the unique item:
SELECT * FROM `testdata` group by timestamp order by timestamp DESC

Your question isn't entirely clear. However if you are trying to find the earliest date for the first occurence of each account name, then see the following query.
SELECT t.*
FROM test t
LEFT JOIN test t1
ON t.date > t1.date
AND t.account_name = t1.account_name
WHERE t1.date IS NULL;
Here's an SQL Fiddle demonstrating the query with your sample data.
Alternatively, if you want to find all account names that occur only once, then see the following query.
SELECT t.*
FROM test t
GROUP BY t.account_name
HAVING COUNT(*) = 1;
Here's an SQL Fiddle demonstrating the query with your sample data.

your question is not much clear but i guess you need below something
select date,os_ver,account_name,count(*) from testdata
group by date,os_ver,account_name

Related

How to fill a SQL column with data (calculated) from another table

I have a question and don't know how to approach the problem exactly.
I have two tables as following:
Clients
| c_id | name | reference |
| ---- | ------- | --------- |
| 1 | ClientA | 1 |
| 2 | ClientB | 1 |
| 3 | ClientC | 2 |
| 4 | ClientD | 2 |
| 5 | ClientE | 1 |
| 1 | ClientF | 3 |
Tour
| t_id | name | count |
| ---- | ------- | ----- |
| 1 | TourA | 3 |
| 2 | TourB | 2 |
| 3 | TourC | 1 |
"Reference" in the "Client" table is defined as foreign key.
Is it possible to fill the column "count" in the table "Tour" with an automated formula where it counts how many times the t_id appears in the "Client" table?
Something like: COUNT(c_id) FROM clients WHERE reference = t_id
I have read about to create a view but not sure how to fetch the data correctly.
Thanks for your help,
Raphael
UPDATE #1:
The workflow as described with the view works perfectly. I'm trying now to fill the column via a trigger but I'm getting an SQL error with the following code:
CREATE TRIGGER client_count
AFTER UPDATE
ON clients FOR EACH ROW
SELECT t.*,
(
SELECT COUNT(*) FROM clients c where c.tour_id = t.tour_id
) AS tours.tour_bookedspace
FROM tours t
The view you have referred to is indeed the way to go here. The view you need to create needs to join the two tables and perform a count aggregation as follows:
CREATE VIEW vwTour
AS
SELECT t.t_id,
t.name,
COUNT(t.name) AS Cnt
FROM tour t
JOIN Clients c
ON t.t_id = c.reference
GROUP BY t_id,
t.name
No you can't. Generated columns can only use data from the same table.
The options you have are:
1. Use a view
You can select from a view that computes the extra value(s) you want. For example:
create view tour_data as
select t.*,
(
select count(*) from clients c where c.reference = t.t_id
) as number_of_clients
from your t
2. Use a trigger
Alternatively, you can add the extra column number_of_clients and populate it using a trigger every time a row is added, modified, or deleted from the table clients.

MYSQL : Group by all weeks of a year with 0 included

I have a question about some mysql code.
I have a table referencing some employees with the date of arrival et the project id. I wanna calculate all the entries in the enterprise and group it by week.
A this moment, I can have this result
Project ID | Week | Count
1 | 2019-S01 | 2
1 | 2019-S03 | 1
2 | 2019-S01 | 1
2 | 2019-S04 | 5
2 | 2019-S05 | 3
2 | 2019-S06 | 2
This is good, but I would like to have all the weeks returned, even if a week has 0 as result :
Project ID | Week | Count
1 | 2019-S01 | 2
1 | 2019-S02 | 0
1 | 2019-S03 | 1
...
2 | 2019-S01 | 1
2 | 2019-S02 | 0
2 | 2019-S03 | 0
2 | 2019-S04 | 5
2 | 2019-S05 | 3
2 | 2019-S06 | 2
...
Here is my actual code :
SELECT
AP.SECTION_ANALYTIQUE AS SECTION,
FS_GET_FORMAT_SEMAINE(AP.DATE_ARRIVEE_PROJET) AS SEMAINE,
Count(*) AS COMPTE
FROM
RT00_AFFECTATIONS_PREV AP
WHERE
(AP.DATE_ARRIVEE_PROJET <= CURDATE() AND Year(AP.DATE_ARRIVEE_PROJET) >= Year(CURDATE()))
GROUP BY
SECTION, SEMAINE
ORDER BY
SECTION
Does anybody have a solution ?
I searched things on internet but didn't find anything accurate :(
Thank you in advance ! :)
The classic way to meet this requirement is to create a referential table to store all possible weeks.
create table all_weeks(week varchar(8) primary key);
insert into all_weeks values
('2019-S01'), ('2019-S02'), ('2019-S03'), ('2019-S04'), ('2019-S05'), ('2019-S06');
Once this is done, you can generate a cartesian product of all possible sections and weeks with a CROSS JOIN, and LEFT JOIN that with the original table.
Given your code snippet, this should look like:
SELECT
s.section_analytique AS section,
w.week AS semaine,
COUNT(ap.section_analytique) AS compte
FROM
(SELECT DISTINCT section_analytique from rt00_affectations_prev) s
CROSS JOIN all_weeks w
LEFT JOIN rt00_affectations_prev ap
ON s.section_analytique = ap.section_analytique AND w.week = FS_GET_FORMAT_SEMAINE(ap.date_arrivee_projet)
GROUP BY s.section_analytique, w.week
ORDER BY s.section_analytique
PS: be careful not to put conditions on the original table in the WHERE clause: this would defeat the purpose of the LEFT JOIN. If you need to do some filtering, use the referential table instead (you might need to add a few columns to it, like the starting date of the week maybe).

Pivot SQL data - groups rows into columns

I have data stored in a mySQL database in the following format:
+------------+------------+-----------+
| id | field | value |
+============+============+===========+
| 1 | first | Bob |
+------------+------------+-----------+
| 1 | last | Smith |
+------------+------------+-----------+
| 2 | first | Jim |
+------------+------------+-----------+
| 2 | last | Jones |
+------------+------------+-----------+
and I would like it returned as follows:
+------------+------------+-----------+
| id | first | last |
+============+============+===========+
| 1 | Bob | Smith |
+------------+------------+-----------+
| 2 | Jim | Jones |
+------------+------------+-----------+
I know this seems like a silly way to store data, but it's just a simple example of what I really have. The table is formatted this way from a WordPress plugin, and I'd like to make it work without having to rewrite the plugin.
From what I've read, I can't use PIVOT with mySql. Is there something similar to PIVOT that I can use to achieve what I'm going for?
Try this pivot query:
SELECT id,
MAX(CASE WHEN field = 'first' THEN value ELSE NULL END) AS first,
MAX(CASE WHEN field = 'last' THEN value ELSE NULL END) AS last
FROM yourTable
GROUP BY id
Follow the link below for a running demo:
SQLFiddle
Try this;)
select
id,
max(if(field='first', value, null)) as first,
max(if(field='last', value, null)) as last
from yourtable
group by id
SQLFiddle DEMO HERE

List Last record of each item in mysql

Each item(item is produced by Serial) in my table has many record and I need to get last record of each item so I run below code:
SELECT ID,Calendar,Serial,MAX(ID)
FROM store
GROUP BY Serial DESC
it means it must show a record for each item which in that record all data of columns be for last record related to each item but the result is like this:
-------------------------------------------------------------+
ID | Calendar | Serial | MAX(ID) |
-------------------------------------------------------------|
7031053 | 2016-05-14 14:05:14 79.5 | N10088 | 7031056 |
7053346 | 2016-05-14 15:17:28 79.8 | N10078 | 7053346 |
7051349 | 2016-05-14 15:21:29 86.1 | J20368 | 7051349 |
7059144 | 2016-05-14 15:50:27 89.6 | J20367 | 7059144 |
7045551 | 2016-05-14 15:15:15 89.2 | J20366 | 7045551 |
7056243 | 2016-05-14 15:25:34 85.2 | J20358 | 7056245 |
7042652 | 2016-05-14 15:18:33 83.9 | J20160 | 7042652 |
7039753 | 2016-05-14 11:48:16 87 | J20158 | 7039753 |
7036854 | 2016-05-14 15:18:35 87.5 | J20128 | 7036854 |
7033955 | 2016-05-14 15:20:45 83.4 | 9662 | 7033955 |
-------------------------------------------------------------+
the problem is why for example in record related to Serial N10088 the ID is "7031053", but MAX(ID) is "7031056"? or also for J20358?
each row must show last record of each item but in my output it is not true!
If you want the row with the max value, then you need a join or some other mechanism.
Here is a simple way using a correlated subquery:
select s.*
from store s
where s.id = (
select max(s2.id)
from store s2
where s2.serial = s.serial
);
You query uses a (mis)feature of SQL Server that generates lots of confusion and is not particularly helpful: you have columns in the select that are not in the group by. What value do these get?
Well, in most databases the answer is simple: the query generates an error as ANSI specifies. MySQL pulls the values for the additional columns from indeterminate matching rows. That is rarely what the writer of the query intends.
For performance, add an index on store(serial, id).
try this one.
SELECT MAX(id), tbl.*
FROM store tbl
GROUP BY Serial
You can try with this also...
SELECT ID,Calendar,Serial
FROM store s0
where ID = (
SELECT MAX(id)
FROM store s1
WHERE s1.serial = s0.serial
);

Returns distinct record in a joins query - Rails 4

I'm trying to get and display an order list including the current status.
#orders = Order.joins(order_status_details: :order_status)
.order('id DESC, order_status_details.created_at DESC')
.select("orders.id, order_status_details.status_id, order_statuses.name, order_status_details.created_at")
It works good but is returning all the rows with order ids duplicated like this:
+----+-----------+----------------------+---------------------+
| id | status_id | name | created_at |
+----+-----------+----------------------+---------------------+
| 8 | 1 | Pending | 2016-01-31 16:33:30 |
| 7 | 3 | Shipped | 2016-02-01 05:01:21 |
| 7 | 2 | Pending for shipping | 2016-01-31 05:01:21 |
| 7 | 1 | Pending | 2016-01-31 04:01:21 |
+----+-----------+----------------------+---------------------+
The correct answer must return uniques ids, for the example above should be the first and second row.
I was already trying with distinct on select, .distinct, .uniq and .group but I'm getting an error.
Thanks.
First of all, I believe your model is "An Order has many OrderStatusDetail". So that is the reason why you have several different name in your result.
So you can modify the query like this:
#orders = Order.joins(order_status_details: :order_status)
.order('id DESC, order_status_details.created_at DESC')
.where('order_status_details.id IN (SELECT MAX(id) FROM order_status_details GROUP BY order_id)')
.select("orders.id, order_status_details.status_id, order_statuses.name, order_status_details.created_at")
Ideally, the where condition is used for selecting just the expected id of order_status_details, I use min_id for example, you can modify it as needed