“分区依据”结果的ID?

时间:2017-07-10 09:59:04

标签: sql sql-server

我正在考虑使用SQL查询,我将使用over (partition by xx)

我想知道如何为每个分区添加一个带有ID的列。 例如,请参见下表:

Name          Country
---------------------------
Mark          USA
Paul          USA
Jennifer      Canada
Carla         Canada
José          Mexico
Pablo         Peru

在此查询之后(使用假设的ID_PARTITION()函数):

select ID_PARTITION(), row_number() over (partition by country), name, country from tableabove;

我会得到:

ID   Row_number()    Name     Country
_______________________________________
1               1    Mark     USA
1               2    Paul     USA
2               1    Jennifer Canada
2               2    Carla    Canada
3               1    José     Mexico
4               1    Pablo    Peru

有关如何实施此类内容的任何线索?

干杯,

弗朗西斯

2 个答案:

答案 0 :(得分:2)

您可以使用如下的dense_rank:

instance of Win32_PnPSignedDriver
{
    ClassGuid = "{4d36e967-e325-11ce-bfc1-08002be10318}";
    CompatID = "SCSI\\Disk";
    Description = "Disk drive";
    DeviceClass = "DISKDRIVE";
    DeviceID = "SCSI\\DISK&VEN_EQLOGIC&PROD_100E-00\\1&1C121344&0&000000";
    DeviceName = "Disk drive";
    DevLoader = NULL;
    DriverDate = "20060621000000.******+***";
    DriverName = NULL;
    DriverProviderName = "Microsoft";
    DriverVersion = "6.1.7601.19133";
    FriendlyName = "EQLOGIC 100E-00 SCSI Disk Device";
    HardWareID = "SCSI\\DiskEQLOGIC_100E-00_________5.2_";
    InfName = "disk.inf";
    IsSigned = TRUE;
    Location = "Bus Number 0, Target Id 0, LUN 0";
    Manufacturer = "(Standard disk drives)";
    PDO = "\\Device\\00000089";
    Signer = "Microsoft Windows";
};

答案 1 :(得分:1)

怎么样:

SELECT DENSE_RANK() OVER ( ORDER BY Country) AS ID
      ,ROW_NUMBER() OVER (PARTITION BY Country ORDER BY Country)  AS RowNumber
      ,name
      ,country
  FROM tableabove