mysql计数新列的出现次数

x7yiwoj4  于 2021-06-18  发布在  Mysql
关注(0)|答案(2)|浏览(341)

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

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

想要的结果

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

我使用vfp odbc驱动程序受到限制

cedebl8k

cedebl8k1#

您应该真正处理应用程序代码中与显示相关的事情。但是,可以将条件聚合与 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小提琴演示

zazmityj

zazmityj2#

您已经用vfp、mysql和odbc标记了这个问题,所以我假设这个问题是关于在vfp和mysql后端中执行这个操作的(因为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

相关问题