从SQL表中选择行,从另一行中选择5行

时间:2013-01-21 13:09:58

标签: sql sql-server

我有三个SQL服务器表,如enter image description here

我需要选择与每个类别相关的categories from LS_categoires where nodeid = 183select only 5 files from LS_files

如果我有两个与node 183相关的类别,则结果应为10 rows 那可能吗?

1 个答案:

答案 0 :(得分:0)

试试这个:

  SELECT
  *  
FROM LS_Categories c 
INNER JOIN
( 
   SELECT 
     *, ROW_NUMBER() OVER(PARTITION BY catid
                          ORDER BY item_id ASC) rownum
   FROM LS_ItemTypes
) l  ON c.catid = l.catid
    AND l.rownum <= 5
INNER JOIN LS_Files f ON l.item_id = f.id
where c.nodeid = 183;

这将为每个类别选择第一个文件。