5

我有一种情况,我需要与INNET JOIN. 这是我遇到的类似情况:

DECLARE @categories AS TABLE(
    CatID INT,
    CategoryName NVARCHAR(100)
);

DECLARE @fooTable AS TABLE(
    ID INT,
    CatID INT,
    Name NVARCHAR(100),
    MinAllow INT,
    Price DECIMAL(18,2)
);

INSERT INTO @categories  VALUES(1, 'Cat1');
INSERT INTO @categories  VALUES(2, 'Cat2');
INSERT INTO @categories  VALUES(3, 'Cat3');
INSERT INTO @categories  VALUES(4, 'Cat4');
INSERT INTO @categories  VALUES(5, 'Cat5');

INSERT INTO @fooTable  VALUES(1, 1, 'Product1', 2, 112.2);
INSERT INTO @fooTable  VALUES(3, 1, 'Product3', 5, 233.32);
INSERT INTO @fooTable  VALUES(6, 1, 'Product6', 4, 12.43);
INSERT INTO @fooTable  VALUES(7, 4, 'Product7', 4, 12.43);
INSERT INTO @fooTable  VALUES(8, 5, 'Product8', 4, 12.43);

这些是我的记录。如您所见,有些分类里面没有任何产品@fooTable。作为下一步,我们有以下SELECT声明:

SELECT * FROM @fooTable ft
INNER JOIN (
    SELECT ROW_NUMBER() OVER (ORDER BY CatID) AS RowNum, * FROM @categories
) AS cat ON (cat.CatID = ft.CatID);

它是一个基本的 JOIN,除了输出还将携带类别的行号。我得到的这个查询的结果如下:

ID   CatID   Name          MinAllow    Price     RowNum   CatID    CategoryName
---- ------- ------------- ----------- --------- -------- -------- -------------
1    1       Product1      2           112.20    1        1        Cat1
3    1       Product3      5           233.32    1        1        Cat1
6    1       Product6      4           12.43     1        1        Cat1
7    4       Product7      4           12.43     4        4        Cat4
8    5       Product8      4           12.43     5        5        Cat5

当您查看该RowNum列时,您会发现这些值对分页不友好。因此,当我尝试按如下方式对该表进行分页时,我得到了不正确的输出:

SELECT * FROM @fooTable ft
INNER JOIN (
    SELECT ROW_NUMBER() OVER (ORDER BY CatID) AS RowNum, * FROM @categories
)AS cat ON (cat.CatID = ft.CatID) AND (cat.RowNum BETWEEN 1 AND 2);

我的实际情况与此类似,但该查询非常复杂,我需要让它与 INNER JOIN 一起使用。我希望我说清楚了。知道我是如何得到这样的工作的吗?

编辑

根据我第一次选择查询的上述结果,我应该能够CatID在我的第二次查询中检索到 1 和 4 的产品。这就是我的目标。

4

1 回答 1

8

一种解决方案可能是下一种解决方案:

SELECT  x.*
FROM
(
        SELECT  ft.*, 
                cat.CategoryName,
                DENSE_RANK() OVER (ORDER BY ft.CatID) AS Rnk
        FROM @fooTable ft
        INNER JOIN @categories cat ON (cat.CatID = ft.CatID)
) AS x
WHERE   x.Rnk BETWEEN 1 AND 2

结果:

ID CatID Name     MinAllow Price   CategoryName Rnk
-- ----- -------- -------- ------- ------------ ---
1  1     Product1 2        112.20  Cat1         1
3  1     Product3 5        233.32  Cat1         1
6  1     Product6 4        12.43   Cat1         1
7  4     Product7 4        12.43   Cat4         2
于 2012-04-17T10:13:06.070 回答