MySQL计数出现到新列

时间:2018-10-23 23:31:19

标签: mysql odbc visual-foxpro

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

示例:

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

想要的结果

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

我只能使用VFP ODBC驱动程序

2 个答案:

答案 0 :(得分:0)

您应该真正在应用程序代码中处理与显示相关的事情。但是,您可以对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

答案 1 :(得分:0)

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

然后,您可以使用以下简单查询从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