Microsoft sql选择不同的某些列

时间:2015-05-27 06:17:05

标签: sql-server sql-server-2008

我正在将mysql查询更改为microsoft sql server 2008查询,为了应用限制,我需要选择累积在每行上的ROW_NUMBER(),然后应用where条件WHERE RowNum >= 0 AND RowNum < 0 + 20来选择a偏差的某些限制。

我的问题是,我不能再选择不同了,因为我的列RowNum与每行不同,这是我的查询:

USE mydatabase
GO

WITH Results_CTE
AS (
    SELECT DISTINCT C.firstname
        ,C.lastname
        ,C.id AS clientid
        ,QC.category_name
        ,QR.id
        ,QR.cid
        ,QR.catid
        ,QR.rhid
        ,ROW_NUMBER() OVER (
            ORDER BY QR.id DESC
            ) AS RowNum
    FROM cms_question_report QR
        ,cms_clients C
        ,cms_questioncategory QC
    WHERE C.id = QR.cid
        AND QR.catid = '3'
        AND QR.catid = QC.id
    )
SELECT *
FROM Results_CTE
WHERE RowNum >= 0
    AND RowNum < 0 + 20

结果是:

╔═══════════╦══════════╦══════════╦═══════════════╦═══════╦═════╦═══════╦══════╦════════╗
║ firstname ║ lastname ║ clientid ║ category_name ║  id   ║ cid ║ catid ║ rhid ║ RowNum ║
╠═══════════╬══════════╬══════════╬═══════════════╬═══════╬═════╬═══════╬══════╬════════╣
║ test      ║ testing  ║      121 ║ Activity Log  ║ 81499 ║ 121 ║     3 ║    0 ║     19 ║
║ test      ║ testing  ║      121 ║ Activity Log  ║ 81498 ║ 121 ║     3 ║    0 ║     20 ║
║ test      ║ testing  ║      121 ║ Activity Log  ║ 81497 ║ 121 ║     3 ║    0 ║     21 ║
║ test      ║ test     ║      120 ║ Activity Log  ║ 81496 ║ 120 ║     3 ║    0 ║     22 ║
║ test      ║ test     ║      120 ║ Activity Log  ║ 81495 ║ 120 ║     3 ║    0 ║     23 ║
║ test      ║ test     ║      120 ║ Activity Log  ║ 81494 ║ 120 ║     3 ║    0 ║     24 ║
║ test      ║ test     ║      120 ║ Activity Log  ║ 81493 ║ 120 ║     3 ║    0 ║     25 ║
╚═══════════╩══════════╩══════════╩═══════════════╩═══════╩═════╩═══════╩══════╩════════╝

我从结果的中间拿了一个例子。我所追求的是例如:

╔═══════════╦══════════╦══════════╦═══════════════╦═══════╦═════╦═══════╦══════╦════════╗
║ firstname ║ lastname ║ clientid ║ category_name ║  id   ║ cid ║ catid ║ rhid ║ RowNum ║
╠═══════════╬══════════╬══════════╬═══════════════╬═══════╬═════╬═══════╬══════╬════════╣
║ test      ║ testing  ║      121 ║ Activity Log  ║ 81497 ║ 121 ║     3 ║    0 ║     21 ║
║ test      ║ test     ║      120 ║ Activity Log  ║ 81496 ║ 120 ║     3 ║    0 ║     22 ║
╚═══════════╩══════════╩══════════╩═══════════════╩═══════╩═════╩═══════╩══════╩════════╝

我尝试按clientid对结果进行分组。我如何实现这一目标?

1 个答案:

答案 0 :(得分:0)

USE ctarspla_mercycs
GO
WITH Results_CTE AS
    (SELECT *, ROW_NUMBER() OVER (ORDER BY CLIENTID DESC) AS RowNum 
        FROM (SELECT DISTINCT 
        C.firstname, 
        C.lastname, 
        C.id as clientid, 
        QC.category_name, 
        QR.catid, 
        QR.rhid 
        FROM 
        cms_question_report QR, 
        cms_clients C, 
        cms_questioncategory QC 
        WHERE C.id=QR.cid 
        AND QR.catid=3 
        AND QR.catid=QC.id) t1)
SELECT * FROM Results_CTE 
WHERE RowNum >= 0 
AND RowNum < 0 + 20