0

当我运行下面的代码时,ROWID 始终为 1。对于具有相同Credit Value的每个项目,我需要 ID 从 1 开始。

;WITH CTETotal AS (SELECT
     TranRegion
    ,TranCustomer
    ,TranDocNo
    ,SUM(TranSale) 'CreditValue'
FROM dbo.Transactions

LEFT JOIN customers AS C 
      ON custregion = tranregion 
      AND custnumber = trancustomer
LEFT JOIN products AS P
      ON prodcode = tranprodcode

GROUP BY
TranRegion
,TranCustomer
,TranDocNo)

SELECT
       r.RegionDesc
      ,suppcodedesc
      ,t.tranreason as [Reason]
      ,t.trandocno as [Document Number]
      ,sum(tranqty) as Qty
      ,sum(tranmass) as Mass
      ,sum(transale) as Sale
      ,cte.CreditValue AS 'Credit Value'
      ,RANK() OVER (PARTITION BY cte.CreditValue ORDER BY cte.CreditValue)AS ROWID

FROM transactions t

LEFT JOIN dbo.Regions AS r    
      ON r.RegionCode = TranRegion  

LEFT JOIN CTETotal AS cte
      ON cte.TranRegion = t.TranRegion
      AND cte.TranCustomer = t.TranCustomer
      AND cte.TranDocNo = t.TranDocNo

GROUP BY 
       r.RegionDesc
      ,suppcodedesc
      ,t.tranreason
      ,t.trandocno
      ,cte.CreditValue

ORDER BY CreditValue ASC

编辑

所有 400 的信用值必须将 ROWID 设置为 1。所有 200 的信用值必须将 ROWID 设置为 2。依此类推。

4

5 回答 5

5

你需要这样的东西吗?

with cte (item,CreditValue)
as
(
select 'a',8 as CreditValue union all
select 'b',18 union all
select 'a',8 union all
select 'b',18 union all
select 'a',8 
) 
select CreditValue,dense_rank() OVER (ORDER BY item)AS ROWID from cte

结果

CreditValue ROWID
----------- --------------------
8           1
8           1
8           1
18          2
18          2

在您的代码中替换

,RANK() OVER (PARTITION BY cte.CreditValue ORDER BY cte.CreditValue)AS ROWID 

经过

,DENSE_RANK() OVER (ORDER BY cte.CreditValue)AS ROWID 
于 2012-07-26T10:11:40.873 回答
3

您不必使用PARTITION,只需DENSE_RANK() OVER (ORDER BY cte.CreditValue)

于 2012-07-26T10:07:30.880 回答
0

我认为问题出在 RANK() OVER (PARTITION BY 子句

您必须按项目而不是 CreditValue 对其进行分区

于 2012-07-26T09:41:04.177 回答
0

试试这个

RANK() OVER (PARTITION BY cte.CreditValue ORDER BY cte.RegionDesc)AS ROWID

于 2012-07-26T09:50:40.033 回答
0

编辑:这里的问题实际上不是子查询的嵌套,它可能基于partition by拥有真正使每一行唯一(或 1)的列

而不是像这样在您的复杂查询中排名

select 
   rank() over(partition by...),
   *
from
   data_source
join table1
join table2
join table3
join table4
order by
   some_column

尝试rank()row_number()在结果数据集上,而不是在其中。

例如,使用上面的查询,以rank()这种方式删除并实现它:

select
   rank() over(partition by...),
   results.*
from (
    select 
       *
    from
       data_source
    join table1
    join table2
    join table3
    join table4
    order by
       some_column
) as results
于 2021-07-28T17:20:17.107 回答