简体   繁体   English

SQL查询-将行值作为列返回

[英]SQL Query - return row values as columns

I have a table: 我有一张桌子:

Part    X   Y   
ABC     1   10  
ABC     2   20  
ABC     3   30  
ABC     4   40  
ABC     5   x   
ABC     6   x   
XYZ     1   50  
XYZ     2   60  
XYZ     3   70  
XYZ     4   80  
XYZ     5   x   
XYZ     6   x   
ETC     1   90  
ETC     2   100 
ETC     3   110 

Id like to select this data in the following way: 我想通过以下方式选择此数据:

Part    1   2   3   4
ABC     10  20  30  40
XYZ     50  60  70  80
ETC     90  110 120 130

Is this possible? 这可能吗?

Notes: 笔记:

  • Header for results = 1,2,3,4 = Field x from the table 结果标题= 1,2,3,4 =表中的字段x
  • FieldX contains values 1 - 18, I'm only interested in 1-4 FieldX包含值1-18,我只对1-4感兴趣
  • I'd later like to also Join this to a product table where I'll be able to specify the results based on the product.Supplier field. 稍后,我还要将其连接到产品表,在该表中,我将能够基于product.Supplier字段指定结果。

I think Subqueries may be the way to go but not experienced in this area. 我认为Subqueries可能是解决之道,但在该领域没有经验。

Thanks for any help offered 感谢您提供的任何帮助

I'm only posting this as the previous answers seem way off. 我只发布此内容,因为以前的答案似乎还很遥远。 Without knowing your RDBMS , you can use MAX with CASE : 无需了解RDBMS ,就可以将MAXCASE使用:

SElECT part,
    MAX(CASE WHEN X = 1 THEN Y END) Y1,
    MAX(CASE WHEN X = 2 THEN Y END) Y2,
    MAX(CASE WHEN X = 3 THEN Y END) Y3,
    MAX(CASE WHEN X = 4 THEN Y END) Y4
FROM YourTable
GROUP BY part

If you're RDBMS will support it, you can use the PIVOT command. 如果您支持RDBMS,则可以使用PIVOT命令。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM