0

我从另一篇文章中获得了这段代码:

SELECT bar
  FROM (SELECT S.subcategoryname As bar, 
               C.CategoryName AS SortName,
               ROW_NUMBER() OVER (PARTITION BY C.CategoryName 
                                      ORDER BY subcategoryname) As RowNum
          FROM category C 
     LEFT JOIN subCategory S ON C.CategoryID = S.CategoryID 
        UNION ALL
        SELECT C.CategoryName As bar, 
               C.CategoryName AS SortName, 
               0
          FROM category C) foo
ORDER BY foo.SortName, RowNum

它有效,但我怎样才能检索到不仅仅是categoryNamesubCategoryName. 有没有办法从所有列中检索数据?

在此处输入图像描述

我的代码:

select  * from (select s.titlu_subcerinta as bar,c.titlu_Cerinta As SortName, ROW_NUMBER() over(partition by c.titlu_Cerinta order by titlu_subcerinta) as RowNum
from cerinteProiect c left join subcerinteProiect s on c.id_cerinta = s.id_cerinta
UNION ALL
select c.titlu_Cerinta As bar, c.titlu_Cerinta As SortName,0
from cerinteProiect c
)
foo
order by
foo.SortName,RowNum
4

1 回答 1

0

正如 OMG Ponies 所说,首先SELECT FROM是从foo. 如果您没有从 C 那里返回所有列,则您的外部查询无法获取它们。

展开内部查询的两个部分以捕获整个表,如下所示:

SELECT * --grab everything you get in the subquery
  FROM (SELECT S.subcategoryname As bar, 
               C.* --note how this grabs EVERYTHING in Category, as you want
               ROW_NUMBER() OVER (PARTITION BY C.CategoryName 
                                      ORDER BY subcategoryname) As RowNum
          FROM category C 
     LEFT JOIN subCategory S ON C.CategoryID = S.CategoryID 
        UNION ALL
        SELECT C.CategoryName As bar, 
               C.*, --this grabs everything again
               0
          FROM category C) foo
ORDER BY CategoryName, RowNum --both of these come from foo - no need to specify it
于 2012-07-15T22:44:45.227 回答