我有一个表T1
,其中包含countryid, stateid, Value
列。
我需要stateid
值的行号,该值具有每个国家/地区的第一个非零值。表格中的数据按CountryId ASC, StateId ASC
排序。
(Countryid, Stateid, Value)
(1, 11, 0)
(1, 12, 1)
(1, 13, 0)
(2, 21, 0)
(2, 22, 0)
(2, 23, 1)
(3, 31, 0)
(3, 32, 10)
(3, 33, 0)
(3, 34, 20)
我需要输出如下。
答案 0 :(得分:1)
可以使用分区
完成;With CTE_T1 As
(
Select
CountryID, StateID, Value,
Row_Number Over (Partition By CountryID Order By Value) As RK
From
T1
Where
IsNull(Values, 0) <> 0
)
Select *
From CTE_T1
Where RK = 1
如果有多个非零值,分区中的order by子句将用于选择记录。
答案 1 :(得分:1)
WITH FormattedT1 AS
(
SELECT Countryid, Stateid, Value, ROW_NUMBER() OVER(PARTITION BY Countryid ORDER BY ...) AS num
FROM T1
WHERE Value > 0
)
SELECT Countryid, Stateid, Value
FROM FormattedT1
WHERE num = 1
答案 2 :(得分:0)
根据所需的结果集进行猜测,如OP中所述,以下查询返回所需的行号&#39;每countryid
:
SELECT countryid, MIN(rn) AS rn
FROM (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY countryid
ORDER BY stateid) AS rn
FROM T1 ) t
WHERE Value <> 0
GROUP BY countryid
所以,我的猜测是,T1
的每个记录在每个countryid
分区中分配了行号。在stateid
分区中最低 countryid
的记录为row number = 1
,下一记录为row number = 2
等。
基于OP的样本数据输出:
countryid rn
---------------
1 2
2 3
3 2