【问题标题】:mysql count occurrences to new columnsmysql计算新列的出现次数
【发布时间】:2018-10-23 23:31:18
【问题描述】:

是否可以进行查询以计算一列中的出现次数并显示不同列中的出现次数?

例子:

+--------+
| Status |
+--------+
| 2      |
+--------+
| 1      |
+--------+
| 2      |
+--------+
| 3      |
+--------+
| 3      |
+--------+
| 2      |
+--------+

想要的结果

+---------+---------+---------+
| status1 | status2 | status3 |
+---------+---------+---------+
| 1       | 3       | 2       |
+---------+---------+---------+

我受限于使用 VFP ODBC 驱动程序

【问题讨论】:

标签: mysql odbc visual-foxpro


【解决方案1】:

您确实应该在应用程序代码中处理与显示相关的事情。但是,您可以将条件聚合与Group By 一起使用:

SELECT 
  COUNT(CASE status WHEN 1 THEN status END) AS status1, 
  COUNT(CASE status WHEN 2 THEN status END) AS status2, 
  COUNT(CASE status WHEN 3 THEN status END) AS status3
FROM your_table_name 

DB Fiddle DEMO

【讨论】:

    【解决方案2】:

    您已使用 VFP、mysql 和 ODBC 标记了该问题,因此我假设问题是关于在具有 mySQL 后端的 VFP 中执行此操作(因为 VFP 自 V6.x 以来没有 ODBC 驱动程序)。而且我还认为您的状态值可能大于 3,可能有间隙但总共小于 256(否则,如果它们是恒定的 1、2、3,您可以简单地进行计数(当 ...然后......结束)作为状态1......像查询)。

    然后,您可以使用以下简单查询从 mySQL 获取结果:

    SQLExec(m.lnYourhandle, 'select status, count(*) as counts'+;
       ' from myTable group by status','crsCounts')
    

    然后用一个简单的代码交叉它。整个代码如下所示:

    Local lnHandle, ix
    
    lnHandle=Sqlstringconnect('Driver={MySQL ODBC 3.51 Driver};Server=localhost;Database=myDataBase;'+;
        'User=myUsername;Password=myPassword;Option=3;')
    SQLExec(m.lnHandle,'select status, Count(*) as counts'+;
        ' from myTable'+;
        ' group by status'+;
        ' order by status','crsCounts')
    SQLDisconnect(0)
    
    
    Local Array laCounts[1], laStruct[Reccount('crsCounts'),4]
    * Get ProductId by transforming it to style
    * 'StatusXXX' as field name, i as fieldtype, 4, 0 as field length
    Select 'Status'+Padl(Status,3,'0'), 'I', 4, 0 ;
        from crsCounts ;
        into Array laStruct
    
    * Get the counts into an array - already ordered by status
    Select counts From crsCounts Into Array laCounts
    * transpose the array from being [rows,1] to [1,cols]
    Dimension laCounts[1, Alen(laCounts,1)]
    
    * create the result cursor using laStructs array and insert data
    Create Cursor crsXTabbed From Array laStruct
    Insert Into crsXTabbed From Array laCounts
    Browse
    

    【讨论】:

      猜你喜欢
      • 2011-08-04
      • 1970-01-01
      • 1970-01-01
      • 2012-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多