Sql server 在SQL Server中将列分组为行

Sql server 在SQL Server中将列分组为行,sql-server,Sql Server,我有数据表,数据如下: Data category ------------------------ apple fruits spinach vegetables mango fruits lion animals grapes fruits tiger animals potato vegetables 我需要一个查询来显示数据,如下所示: vegetables spinach po

我有数据表,数据如下:

Data         category
------------------------
apple        fruits
spinach      vegetables
mango        fruits
lion         animals
grapes       fruits
tiger        animals
potato       vegetables
我需要一个查询来显示数据,如下所示:

vegetables
spinach
potato 
fruits   
mango               
grapes
animals
lion       
tiger 

首先,您必须正确地设计模式,我认为它可能会帮助您

IF OBJECT_ID('dbo.category') IS NOT NULL
    DROP TABLE category

CREATE TABLE category (
    categoryID INT Identity PRIMARY KEY
    ,categoryName VARCHAR(200)
    )

INSERT  INTO category(categoryName)
SELECT 'fruits'    Union all 
SELECT 'vegetables'Union all
SELECT 'animals'

SELECT * from category


IF OBJECT_ID('dbo.Datacategory') IS NOT NULL
Drop Table Datacategory

CREATE TABLE Datacategory (
    DatacategoryID INT Identity
    ,categoryID INT CONSTRAINT FK_Datacategory_category FOREIGN KEY REFERENCES category(categoryID)
    ,Data VARCHAR(200)
    )

INSERT INTO Datacategory(Data,categoryID)
SELECT     'apple'    ,1  Union all
SELECT     'spinach'  ,2  Union all
SELECT     'mango'    ,1  Union all
SELECT     'lion'     ,3  Union all
SELECT     'grapes'   ,1  Union all
SELECT     'tiger'    ,3  Union all
SELECT     'potato'   ,2
查询以获得所需的结果

SELECT ISNULL(CAST(NULLIF(CASE 
                    WHEN RNo = 1
                        THEN categoryID
                    ELSE ''
                    END, '') AS VARCHAR), '') AS categoryID
    ,Data
FROM (
    SELECT D.categoryID
        ,D.Data
        ,ROW_NUMBER() OVER (
            PARTITION BY D.categoryID ORDER BY D.categoryID
            ) AS Rno
    FROM Datacategory d
    INNER JOIN category c ON c.categoryID = d.categoryID
    ) Dt
ORDER BY Dt.categoryID
输出

categoryID  Data
----------------
1           apple
            mango
            grapes
2           potato
            spinach
3           lion
            tiger

我不明白。你想要什么?我看不到数据和类别之间的关系