我的数据表包含如下数据:
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
答案 0 :(得分:2)
首先,您必须正确设计架构,我认为它可能会对您有所帮助
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