在SQL中查找表中最常用的值

时间:2018-06-07 04:22:55

标签: sql sql-server sql-server-2008

CREATE TABLE Temp_Account
(
   ID Int IDENTITY(1,1),
   AccountNo Varchar(500)
)

.......................................

INSERT INTO Temp_Account
SELECT 'AE000111'
UNION ALL
SELECT 'AE000112'
UNION ALL
SELECT 'AE000113'
UNION ALL
SELECT 'AE000114'
UNION ALL
SELECT 'AE000115'

........................................

 CREATE PROCEDURE Temp_AccountProc
(
   @AccountNo    Varchar(500)
)
AS
BEGIN

   SELECT ID
   FROM   Temp_Account
   WHERE  AccountNo     =      @AccountNo

  END


   EXEC Temp_AccountProc 'AE000111'

   EXEC Temp_AccountProc 'AE000112'

   EXEC Temp_AccountProc 'AE000113'

   EXEC Temp_AccountProc 'AE000111'

   EXEC Temp_AccountProc 'AE000111'

   EXEC Temp_AccountProc 'AE000112'

我想知道表中最常用的值。是否有任何DMV或任何方法来查找给定的输出?

 ------------------------------------
    AccountNo          UsedCount
  ------------------------------------

      AE000111            3

      AE000112            2

      AE000113            1

2 个答案:

答案 0 :(得分:2)

  1. 向表中添加新列或创建另一个临时表,其列为UsedCount和AccountNo,
  2. 在您的程序中,当选择了帐户号时,也选择该帐号的已用计数列值
  3. 增加使用的次数
  4. 执行更新语句以更新该AccountNo的使用计数

答案 1 :(得分:1)

试试这个:

  1. 添加[UsedCount]列
  2. 当呼叫程序设置[UsedCount] + 1
  3. CREATE TABLE Temp_Account
    (
       ID Int IDENTITY(1,1),
       AccountNo Varchar(500),
       [UsedCount]  int
    )
    INSERT INTO Temp_Account
    SELECT 'AE000111',0
    UNION ALL
    SELECT 'AE000112',0
    UNION ALL
    SELECT 'AE000113',0
    UNION ALL
    SELECT 'AE000114',0
    UNION ALL
    SELECT 'AE000115',0
    ;
    
    CREATE PROCEDURE Temp_AccountProc
    (
       @AccountNo    Varchar(500)
    )
    AS
    BEGIN
    
       SELECT ID
       FROM   Temp_Account
       WHERE  AccountNo     =      @AccountNo
    
       update Temp_Account
       set [UsedCount] = [UsedCount] +1
       WHERE  AccountNo     =      @AccountNo
    
    END
    
       EXEC Temp_AccountProc 'AE000111';
       EXEC Temp_AccountProc 'AE000112';
       EXEC Temp_AccountProc 'AE000113';
       EXEC Temp_AccountProc 'AE000111';
       EXEC Temp_AccountProc 'AE000111';
       EXEC Temp_AccountProc 'AE000112';
    
       select * from Temp_Account
       where [UsedCount] > 0;
    

    <强>结果:

    | ID | AccountNo | UsedCount|
    |----|-----------|-------------|
    |  1 |  AE000111 |           3 |
    |  2 |  AE000112 |           2 |
    |  3 |  AE000113 |           1 |
    

    SQL Fiddle Demo Link