简体   繁体   English

根据SQL Server中的行值在查询中分隔列

[英]Separating a column as a result in a query basing from row values in SQL Server

Since I am a newbie, I don't know how to name this question correctly. 由于我是新手,所以我不知道如何正确地命名这个问题。

Suppose I have a table of fruits like this below. 假设我在下面有一张这样的水果表。

id  color   |name
------------------------
1   red     |apple
2   yellow  |banana
3   red     |strawberry
4   red     |red grapes
5   yellow  |mango

What type of select statement in SQL Server do I have to code to produce a query result like this: 我必须对SQL Server中的哪种类型的select语句进行编码才能产生如下查询结果:

red        | yellow
--------------------
apple      |banana 
strawberry |mango
red grapes |

I am trying to make a query in Microsoft Access database. 我试图在Microsoft Access数据库中进行查询。

All I wanted to do is to make a query that would separate the red colored fruits from the yellow ones in columns. 我要做的就是查询将列中红色和黄色水果分开的查询。

It's not exactly the result set you wanted, but it might be close enough? 它不完全是您想要的结果集,但它可能足够接近?

SELECT (SELECT Name FROM Fruit Where Color = 'red'),
       (SELECT Name FROM Fruit Where Color = 'yellow')

UPDATE UPDATE

The solution above does not work in Access, but the one below should: 上面的解决方案在Access中不起作用,但是下面的解决方案应该:

SELECT 
IIF(Color = 'red', Name, '') AS 'Red',
IIF(Color = 'yellow', Name, '') AS 'Yellow' 
FROM Fruits;

Try this 尝试这个

SELECT Isnull(CASE color
                WHEN 'red' THEN name
              END, '') red,
       Isnull(CASE color
                WHEN 'yellow' THEN name
              END, '') yellow
FROM   fruits 

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

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