我有一个表中的客户列表,我想为每个客户分配一个序列号并将其保存到另一个表中。 但是,序列应该每个月重新开始。
目前,我有这个问题:
INSERT INTO tblSerialNo
SELECT CustomerNo
,FORMAT(getdate(), 'yyyyMM')
,ROW_NUMBER() OVER (ORDER BY CustomerNo ASC) AS SerialNo
FROM tblCustomer
但是,即使月份发生了变化,SerialNo列上的序列仍在继续。
当前输出:
--------------------------
|Customer|Month |SerialNo|
|--------+------+--------|
|17000001|201710|00001 |
|17000002|201710|00002 |
|17000003|201710|00003 |
|17000004|201710|00004 |
|17000005|201710|00005 |
|17000001|201710|00006 |
|17000002|201710|00007 |
|17000003|201710|00008 |
|17000004|201710|00009 |
|17000005|201710|00010 |
|17000001|201711|00011 |
|17000002|201711|00012 |
|17000003|201711|00013 |
|17000004|201711|00014 |
|17000005|201711|00015 |
--------------------------
期望的输出:
--------------------------
|Customer|Month |SerialNo|
|--------+------+--------|
|17000001|201710|00001 |
|17000002|201710|00002 |
|17000003|201710|00003 |
|17000004|201710|00004 |
|17000005|201710|00005 |
|17000001|201710|00006 |
|17000002|201710|00007 |
|17000003|201710|00008 |
|17000004|201710|00009 |
|17000005|201710|00010 |
|17000001|201711|00001 |
|17000002|201711|00002 |
|17000003|201711|00003 |
|17000004|201711|00004 |
|17000005|201711|00005 |
--------------------------
请帮忙。提前谢谢。
答案 0 :(得分:2)
在PARTITION BY
子句之前添加ORDER BY
:
INSERT INTO tblSerialNo
SELECT CustomerNo
,FORMAT(getdate(), 'yyyyMM')
,ROW_NUMBER() OVER (PARTITION BY FORMAT(getdate(), 'yyyyMM') ORDER BY CustomerNo ASC) AS SerialNo
FROM tblCustomer
答案 1 :(得分:1)
你可以做这样的事情
INSERT INTO tblSerialNo
select customerno,[Month],
ROW_NUMBER() OVER (partition by [Month] ORDER BY CustomerNo ASC) AS SerialNo from
(
SELECT CustomerNo ,FORMAT(getdate(), 'yyyyMM')as [Month] FROM tblCustomer
)as a
答案 2 :(得分:0)
INSERT INTO tblSerialNo
SELECT CustomerNo
,FORMAT(getdate(), 'yyyyMM')
,ROW_NUMBER()OVER(Partition By FORMAT(getdate(), 'yyyyMM') Order By CustomerNo ASC)As SerialNo
FROM tblCustomer