MySQL 按值选择计数

发布于 2024-12-04 03:27:08 字数 180 浏览 1 评论 0原文

我有这个 mysql 表:

DATE | VALUE

我希望成为一个选择,它向我显示以下信息:

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

有什么想法可以实现这一点吗?

I have this mysql table:

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

伪装你 2024-12-11 03:27:08
SELECT date,
       COUNT(*),
       COUNT( IF( value = 1, 1, NULL ) ),
       COUNT( IF( value = 2, 1, NULL ) )
FROM my_table
SELECT date,
       COUNT(*),
       COUNT( IF( value = 1, 1, NULL ) ),
       COUNT( IF( value = 2, 1, NULL ) )
FROM my_table
海之角 2024-12-11 03:27:08

我认为使用 SUM() 你可以获得更简洁的代码。因为它对行的各个表达式的值求和。

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

官方文档可以在此处找到。

I think with SUM() you can get neater code. 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.

清欢 2024-12-11 03:27:08
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`

当没有匹配时,CASE 表达式将为空。 COUNT() 不计算空值。

我想您可能需要动态数量的列,数据中找到的每个值对应一列。 这在 SQL 中是不可能的。在编写查询时必须知道这些列。

因此,您有两种选择来获取每个值的小计:

  • 首先查询 value 所有行中的不同值,并动态构建 SQL 查询,在选择列表中为每个不同值附加一列你想举报。然后运行此 SQL 查询。

  • 或者,将所有行作为行获取。计算应用程序代码中每个值的小计。

另一种选择是按组计算小计,并包括总计:

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

但这不会按照您的要求报告列中的小计,而是报告行中的小计。

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. Nulls are not counted by 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. 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. Then run this SQL query.

  • 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文