简体   繁体   English

MySQL从一个表创建两列

[英]MySQL Create two columns from a table with one column

I am really new to MySQL, below is one of my first statement basically:) 我对MySQL真的很陌生,以下基本上是我的第一条声明之一:)

I need help. 我需要帮助。

I have this table definition in mysql: 我在mysql中有此表定义:

id | id | item_id | item_id | price | 价格| def = could be A or B def =可以是AB

I need to build a new table with two columns out of this one where I will have items grouped by price and separated into items with def = A and def = B 我需要建立一个新表,其中有两列,其中我将按价格分组的项目分为def = A和def = B的项目

I've tried to use self join and it creates two columns, but it groups only by price of def = A, not distinctly by price of A and price of B. 我尝试使用自连接并创建了两列,但它仅按def = A的价格进行分组,而不按A的价格和B的价格进行分组。

This is where I've gotten so far: 到目前为止,这是我到达的地方:

SELECT a.`id` as A_id,  a.`item_id` as A_ITEM_id, a.`def` as A_def, a.price as A_PRICE,
b.`id` as B_id,  b.`item_id` as B_ITEM_id, b.`def` as B_def, b.price as B_PRICE

FROM table as a, table as b where 
a.`def` = 'A' AND b.`def` = 'B' GROUP by A_PRICE;

I've tried to group by A_PRICE,B_PRICE - doesn't really work. 我尝试按A_PRICE,B_PRICE分组-确实没有用。

you need a case based aggregation to convert def row values into columns 您需要基于case based aggregation以将def行值转换为列

SQL Fiddle SQL小提琴

select item_id, price,
       max(case when def='A' then 'A' end) as A, 
       max(case when def='B' then 'B' end) as B
from table1
group by item_id, price

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 mysql-表的两列和另一列的计数 - mysql - count of two columns of a table and one column from another mysql:从一列创建多个列 - mysql: create multiple columns from one column 在mysql中创建表,其中一列包含另外两列的值的总和 - Create table in mysql with one column containing sum of another two columns value 如何将两个mysql表列添加到datagridview中的一列? - How to add two mysql table columns to one column in datagridview? MySQL选择两列之一匹配的位置,并从另一张表中按列排序 - MySQL select where one of two columns matches and order by column from another table MySQL-从表中选择两列匹配的行。 如果不存在,则选择具有一列的行 - MySQL - Selecting row with two columns match from a table. If doesn't exist select row with one column 将一个表的两列连接到另一表的一列 - Join two columns from one table to one column from another Mysql需要从table1中获取一列两次,然后通过table2的两个不同列对它们进行排序 - Mysql need to get one column two times from table1 and sort them by two different columns of table2 MySQL查询以查找一个表中一列的值是否在另一表中两列的两个值之间 - MySQL query to find if a value of one column in one table is between two values in two columns on another table MySQL尝试从其他两个表的列创建一个表 - MySql Try to create a table from columns from two other tables
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM