计算 SQL 中的值有多少行?
Count how many rows are for a value in SQL?
我有一个 table 看起来像这样:
[ContractId] [ContractDate] [SnapshotTimeId] [DaysPastDue] [Exposure]
Int(not unique) Datetime Int(format20160431) Int Int
table 按 ContractId、ContractDate 排序。
现在,我想添加第 6 列,我们称它为 Unique,第一个 ContractId 值的值为 1,然后加 1 直到它碰到下一个 ContractId。基本上,我想知道每个 ContractId 有多少行,然后将这些值递增地放在一列中。
编辑:我希望输出看起来像这样
>DocumentId ContractDate SnapshottimeId DPD Exposure Unique
>1 31-Aug-15 31-Aug-15 0 500 1
>1 31-Aug-15 30-Sep-15 5 450 2
>1 31-Aug-15 31-Oct-15 35 450 3
>1 31-Aug-15 30-Nov-15 7 350 4
>1 31-Aug-15 31-Dec-15 37 350 5
>1 31-Aug-15 31-Jan-16 67 340 6
>2 31-Aug-15 30-Jun-14 3 800 1
>2 31-Aug-15 31-Jul-14 15 760 2
>2 31-Aug-15 31-Aug-14 45 750 3
>2 31-Aug-15 30-Sep-14 75 750 4
>2 31-Aug-15 31-Oct-14 0 630 5
>2 31-Aug-15 30-Nov-14 15 590 6
>2 31-Aug-15 31-Dec-14 45 580 7
我想你想要 row_number()
:
select t.*,
row_number() over (partition by contractid order by contractdate) as seqnum
from t;
这将增加一个增量值,这就是我认为您所描述的。
如果您只想计算每行中每个合约的行数,请使用:
select t.*,
count(*) over (partition by contractid) as cnt
from t;
如果合同有六行,这将在每行中放置“6”。
which has value 1 for the first ContractId value then adds 1 until it bumps across the next ContractId
RowNumber 就可以了
select *,
Row_number() over (partition by contractid order by contractid) as countt
from
table
如果您想知道 table 中的行号,只需使用:
Select ContractId,
ContractDate,
SnapshotTimeId,
DaysPastDue,
Exposure,
row = ROW_NUMBER() OVER(ORDER BY [ContractId] asc) AS Row
From YourTable
我有一个 table 看起来像这样:
[ContractId] [ContractDate] [SnapshotTimeId] [DaysPastDue] [Exposure]
Int(not unique) Datetime Int(format20160431) Int Int
table 按 ContractId、ContractDate 排序。
现在,我想添加第 6 列,我们称它为 Unique,第一个 ContractId 值的值为 1,然后加 1 直到它碰到下一个 ContractId。基本上,我想知道每个 ContractId 有多少行,然后将这些值递增地放在一列中。
编辑:我希望输出看起来像这样
>DocumentId ContractDate SnapshottimeId DPD Exposure Unique
>1 31-Aug-15 31-Aug-15 0 500 1
>1 31-Aug-15 30-Sep-15 5 450 2
>1 31-Aug-15 31-Oct-15 35 450 3
>1 31-Aug-15 30-Nov-15 7 350 4
>1 31-Aug-15 31-Dec-15 37 350 5
>1 31-Aug-15 31-Jan-16 67 340 6
>2 31-Aug-15 30-Jun-14 3 800 1
>2 31-Aug-15 31-Jul-14 15 760 2
>2 31-Aug-15 31-Aug-14 45 750 3
>2 31-Aug-15 30-Sep-14 75 750 4
>2 31-Aug-15 31-Oct-14 0 630 5
>2 31-Aug-15 30-Nov-14 15 590 6
>2 31-Aug-15 31-Dec-14 45 580 7
我想你想要 row_number()
:
select t.*,
row_number() over (partition by contractid order by contractdate) as seqnum
from t;
这将增加一个增量值,这就是我认为您所描述的。
如果您只想计算每行中每个合约的行数,请使用:
select t.*,
count(*) over (partition by contractid) as cnt
from t;
如果合同有六行,这将在每行中放置“6”。
which has value 1 for the first ContractId value then adds 1 until it bumps across the next ContractId
RowNumber 就可以了
select *,
Row_number() over (partition by contractid order by contractid) as countt
from
table
如果您想知道 table 中的行号,只需使用:
Select ContractId,
ContractDate,
SnapshotTimeId,
DaysPastDue,
Exposure,
row = ROW_NUMBER() OVER(ORDER BY [ContractId] asc) AS Row
From YourTable