简体   繁体   English

MYSQL选择按值计数

[英]MYSQL select count by value

I have this mysql table: 我有这个mysql表:

DATE | VALUE

and I wish to become a select which shows me this information as: 我希望成为一个选择,向我显示这些信息:

DATE | COUNT TOTAL | COUNT VAL=1 | COUNT VAL=2

Any ideas how I can achieve this? 我有什么想法可以达到这个目的吗?

Thanks! 谢谢!

SELECT date,
       COUNT(*),
       COUNT( IF( value = 1, 1, NULL ) ),
       COUNT( IF( value = 2, 1, NULL ) )
FROM my_table

I think with SUM() you can get neater code. 我认为使用SUM()可以获得更整洁的代码。 Since it sums the values respective expression for row. 因为它将行的各个表达式的值相加。

SELECT date,
   COUNT(*),
   SUM( value = 1 ),
   SUM( value = 2 )
FROM my_table

Official Documentation can be found here . 官方文档可以在这里找到。

SELECT `date`, COUNT(*) AS `COUNT TOTAL`, 
  COUNT(CASE `value` WHEN 1 THEN `value` END) AS `COUNT VAL=1`
  COUNT(CASE `value` WHEN 2 THEN `value` END) AS `COUNT VAL=2`
FROM mytable
GROUP BY `date`

The CASE expressions will be null when there is no match. 没有匹配时,CASE表达式将为null。 Nulls are not counted by COUNT() . NUNT不计入COUNT()

I imagine you might want a dynamic number of columns, one column for each value found in the data. 我想你可能想要一个动态数量的列,数据中找到的每个值都有一列。 This is not possible in SQL. 这在SQL中是不可能的。 The columns must be known at the time you write the query. 在编写查询时必须知道列。

So you have two options to get subtotals per value: 因此,您有两个选项可以获得每个值的小计:

  • First query the distinct values from all rows of value and construct an SQL query dynamically, appending one column in the select-list for each distinct value you want to report. 首先查询所有值行中的不同value并动态构造SQL查询,在select-list中为要报告的每个不同值附加一列。 Then run this SQL query. 然后运行此SQL查询。

  • Alternatively, fetch all the rows as rows. 或者,将所有行作为行获取。 Count the subtotals per value in application code. 计算应用程序代码中每个值的小计。

One further alternative is to count subtotals by groups, and include totals: 另一个替代方法是按组计算小计,并包括总计:

SELECT `value`, `date, COUNT(*) AS `COUNT SUBTOTAL`
FROM mytable
GROUP BY `value`, `date` WITH ROLLUP

But that doesn't report the subtotals in columns as you requested, it reports the subtotals in rows. 但是,这并不按您的要求报告列中的小计,它会按行报告小计。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM