我正在使用C#中的一个Windows应用程序。在那里,我想在表格布局面板中显示类别明智的书籍图像。我希望每个类别显示5本图书图像。
我用来检索类别明智的书的查询是
WITH CategoryCTE AS (
SELECT
BookName,
ROW_NUMBER() OVER (
PARTITION BY CategoryName
ORDER BY CategoryName DESC
) AS CTE_Order
FROM BookMaster
)
SELECT bm.BookName,bm.BookImage, cm.CategoryName, scm.SubCategoryName
FROM
CategoryCTE
INNER JOIN BookMaster bm ON CategoryCTE.BookName = bm.BookName
INNER JOIN CategoryMaster cm ON bm.CategoryName = cm.Oid
INNER JOIN SubCategoryMaster scm ON bm.SubCategoryName = scm.Oid
WHERE CategoryCTE.CTE_Order < 6
GROUP BY cm.CategoryName, scm.SubCategoryName, bm.BookName,bm.BookImage
这个查询给了我正确的输出,即它给了我每个类别的5本书。 但问题是,我想在表格面板中显示书籍图像,第1行将有5个类别1的书籍图像,第2行具有类别2的书籍图像,依此类推。现在我的数据库中有4个书籍类别。表格布局面板的行取决于数据库中的类别表,表格列是固定的,即第一列是类别名称,另外5列是书籍图像。
我希望我已经正确解释了我的问题。请为我提出任何解决方案。 提前致谢。
答案 0 :(得分:1)
如果您希望结果如下所示:
CategoryName Book1 Book2 Book3 Book4 Book5
------------ ----------- --------------- -------------- ------------- ------------
Cat1 Image#6.jpg Image#61.jpg Image#62.jpg Image#63.jpg Image#64.jpg
Cat2 Image#5.jpg Image#51316.jpg Image#5136.jpg Image#516.jpg Image#56.jpg
以下查询应该这样做:
WITH CategoryCTE AS (
SELECT
BookName,
ROW_NUMBER() OVER (
PARTITION BY CategoryName
ORDER BY CategoryName DESC, BookName
) AS CTE_Order
FROM BookMaster
)
SELECT CategoryName, [1] AS Book1, [2] AS Book2, [3] AS Book3, [4] AS Book4, [5] AS Book5
FROM
(SELECT bm.BookImage, cm.CategoryName, c.CTE_Order FROM
CategoryCTE c
INNER JOIN BookMaster bm ON c.BookName = bm.BookName
INNER JOIN CategoryMaster cm ON bm.CategoryName = cm.Oid
INNER JOIN SubCategoryMaster scm ON bm.SubCategoryName = scm.Oid
WHERE c.CTE_Order < 6
GROUP BY cm.CategoryName, bm.BookImage, c.CTE_Order
) Sub
PIVOT (MAX(BookImage) FOR CTE_Order IN ([1],[2],[3], [4],[5])) AS PivotTable