I have a table where it has Size and Price for each product. There could be multiple sizes with prices. I want to read size and price with ":" separated while each size:price is separated by commas for each product.
If I read it using SQL query I get the following.
PRODUCT_ID SIZE PRICE
001 L 20
001 S 15
002 M 10
002 L 20
002 S 5
I want to read the following as follows :
PRODUCT SIZE_PRICE
001 L:20,S:15
002 M:10,L:20,S:5
What is the best way to do this ?
You can try to use group_concat with CONCAT
Schema (MySQL v5.7)
CREATE TABLE T(
PRODUCT_ID varchar(50),
SIZE varchar(50),
PRICE int
);
INSERT INTO T VALUES ('001','L',20);
INSERT INTO T VALUES ('001','S',15);
INSERT INTO T VALUES ('002','M',10);
INSERT INTO T VALUES ('002','L',20);
INSERT INTO T VALUES ('002','S',5);
Query #1
SELECT PRODUCT_ID,
GROUP_CONCAT(CONCAT(SIZE,':',PRICE)) 'SIZE_PRICE'
FROM T
GROUP BY PRODUCT_ID;
| PRODUCT_ID | SIZE_PRICE |
| ---------- | ------------- |
| 001 | L:20,S:15 |
| 002 | M:10,L:20,S:5 |
View on DB Fiddle
Related
I am trying to create a table which holds the historical running times (in minutes) for a host of athletes. The table holds a foreign key to the persons name, along with storing their new running time and previous running time, along with the date the run was performed.
I am trying to keep all records of runners in the same table. I want to refer to the old running time in the new entry of when a new running time is complete. I am struggling on how this relationship will work.
Below is a table explaining what I am trying to achieve.
|Name_ID {FK}|Completion_Date|New_Time|Old_Time|
| 001 | 16/02/2019 | 123 | 108 |
| 001 | 16/03/2019 | 136 | 123 |
As you the table shows, the new average from the 16/02/2019 appears as the old average in 16/03/2019.
My question is how would I construct this relationship? Is it possible to make this a relationship?
OR
Is there a more efficient way? I.e Have the following table:
|Name_ID {FK}|Completion_Date|New_Time|
| 001 | 16/02/2019 | 123 |
| 001 | 16/03/2019 | 136 |
and create a query that could use the Name_ID and completion_Date attributes to produce an output that made:
|Name_ID {FK}|Completion_Date|New_Time|Old_Time|
| 001 | 16/02/2019 | 123 | 108 |
Any help will be appreciated.
If you don't have a Mysql 8.x Server you can use this.
CREATE TABLE table1
(`Name_ID {FK}` int, `Completion_Date` varchar(10), `New_Time` int)
;
INSERT INTO table1
(`Name_ID {FK}`, `Completion_Date`, `New_Time`)
VALUES
(001, '16/01/2019', 108),
(001, '16/02/2019', 123),
(001, '16/03/2019', 136)
;
And you can use this
select `Name_ID {FK}`,`Completion_Date`,#quot old_time, #quot:=`New_Time` new_time
from table1 p,(SELECT #quot := 0) r
order by `Name_ID {FK}`,`Completion_Date`;
to get This result:
Name_ID {FK} Completion_Date old_time new_time
1 16/01/2019 0 108
1 16/02/2019 108 123
1 16/03/2019 123 136
It is based on this
Simulate lag function in MySQL
You can use lead/lag analytical functions to get the desired result -
Using your Name| completion_date| new_time runner_data table,
create a new table with below sql:
insert into new_table select name, completion_date, new_time, lag(completion_date) over ( partition by name order by completion_date desc) as old_time from runner_data;
I want to find the count on "The number of times a replacement occurred for each component."
For example,
Component_ID | Replacement_ID
001 | NULL
002 | 001
003 | 002
004 | 003
005 | Null
Result :
Component_ID | Number of time a replacement already occurred
004 | 3
005 | 0
Normally you are supposed to have at-least two tables. A components table which contains your components with Component_ID as the primary field together with other fields such as component_name and another table probably called component_replacements which contains a primary field ID such as component_replacement_id together with component_id and other fields such as replacement date. Component_ids can occur more than once in this table. This would allow you to have a basic query such as:
SELECT Component_ID, IFNULL( total,0) replacements FROM
(
SELECT Component_ID, COUNT(*) total
FROM component_replacements GROUP BY Component_ID
) replacements ON components.Component_ID = replacements.Component_ID
I have some question : "insert data in different table but have same id (auto_increment)"
This is my twice table
student
---------------------- id | name | class|
----------------------
score
--------------------------------------------- id | math | english | physical | year |
---------------------------------------------
I have some data like:
John , A , 90 ,80 ,70 ,2015
John , A , 70 ,90 ,50 ,2016
I want result Like:
student
---------------------- id | name | class|
---------------------- 1 | John | A |
----------------------
score
--------------------------------------------- id | math | english | physical | year |
---------------------------------------------
1 | 90 | 80 | 70 |2015 1 | 70 | 90 | 50 |2016
Because table of student's "id" use Auto_increment
If I want twice table have same id when I insert data
What SQL can I use ??
(I think mysql_insert_id() is Solution but not sure...)
Thank help !!
I hope you are looking for the query to do so.First of all use PDO or mysqli for interacting with the database.Here I use PDO.
function my_select($query)
{
global $dbserver,$dbuser,$dbpwd,$dbname;
$dbh= new PDO('mysql:host='.$dbserver.';dbname='.$dbname.'',$dbuser,$dbpwd);
$rs=$dbh->prepare($query); //prepared statements have numerous advantages over executing sql statements directly
$rs->execute();
return $db->lastInsertId(); //returns last inserted id of current db connection
}
And the query can be,
$l_id=my_select(query1) // query to insert into student
$query2="INSERT INTO score (id,...) VALUES ('".$l_id."',...)" ;
my_select(query2);
If you are using Auto Increament id in both tables than you need to add a column in score table for reference of studentid. For example:
Insert into student (name) values ('test');
Than use:
mysql_insert_id();
In last insert data into score table:
Insert into score (yourcolumns, studentid) values (yourcolumnvalue, last_inserted_id);
Side note: instead of mysql_*
functions use mysqli_* or PDO becuase mysql_* is deprecated and not available in PHP 7.
I have two tables, average_table and position_table. They have two column each. I would like to copy sorted data from average_table into position_table as shown below
The average_table looks like this
std_id avr
001 23.4
002 34.7
003 13.9
004 56.8
then the position_table should look like this:
std_id avr
004 56.8
002 34.7
001 23.4
003 13.9
When I used the following sql queries, the result was no different between average_table and position_table. Can some one help me out please?
try {
String str = "insert into POSITION_TABLE select * from AVERAGE_TABLE ORDER BY avr DESC";
rs = st.executeQuery(str);
}
catch(SQLException ce){System.out.print(ce)}
In the SQL world rows aren't really sorted. There might be a way to do this in MySQL (in SQL server, I think a clustered might do it - but for another reason than getting the rows in order).
In other words, an inserted row is not guaranteed to have a specific order. As SQL is declarative, you have to declare how to order it when you query.
I don't understand what you're trying to achieve with the position table - to me it looks like an exact duplicate of the average table and you're getting the data in ranked order already with your query using the order by. Just use order by when you need the data ordered.
create table average_table
( std_id int not null,
avr decimal(8,2) not null
);
insert average_table (std_id,avr) values (1,23.4),(2,34.7),(3,13.9),(4,56.8);
create table position_table
( id int auto_increment primary key,
std_id int not null,
avr decimal(8,2) not null
);
insert into position_table(std_id,avr) select std_id,avr from average_table order by avr desc;
select * from position_table;
+----+--------+-------+
| id | std_id | avr |
+----+--------+-------+
| 1 | 4 | 56.80 |
| 2 | 2 | 34.70 |
| 3 | 1 | 23.40 |
| 4 | 3 | 13.90 |
+----+--------+-------+
I have this table :
/* Create a table called users */
CREATE TABLE users(Id integer PRIMARY KEY, Name text, country text);
/* Create few records in this table */
INSERT INTO users VALUES(1,'Tom','Canada');
INSERT INTO users VALUES(2,'Lucy','USA');
INSERT INTO users VALUES(3,'Frank','USA');
INSERT INTO users VALUES(4,'Jane','Canada');
INSERT INTO users VALUES(5,'Robert','Italy');
COMMIT;
I want a query that displat this result :
+---+--------+--------+
| 1 | Tom | Canada |
+---+--------+--------+
| 4 | Jane | Canada |
| 3 | Frank | USA |
| 2 | Lucy | USA |
| 5 | Robert | Italy |
+---+--------+--------+
that mean classification users by countries. For that I use this query :
SELECT * FROM users group by country;
but the result is not satisfying, because the group by delete duplicate rows.
Any advice will be nice.
Your desired output looks more like a specific ordering than a grouping. For ordering use ORDER BY:
SELECT * FROM users ORDER BY country;