mysql - 如何向 SQL 查询中的列添加值?

标签 mysql sql

我有一道我不太明白的作业题。我被要求进行一个查询,该查询将在同一行上产生其他值,据我所知,这意味着添加更多列。我不知道该怎么做,不幸的是,这里对现有问题的回答似乎没有回答我的问题,也许我遗漏了一些东西(我是一个 SQL 菜鸟)。

问题是:

Write a query that returns the following data: a row per date and abtest, where each row has the impressions and clicks for all the variants and for the control. Variants are identified as vrows where variant_id is not zero, Control is identified as rows where the variant_id is 0.

E.g. for the below data, the query will return:

2018-01-01,2,32323,212,95262,354

2018-01-01,5,76675,5454,675675,5454

2018-01-02,2,0,0,7834,99

2018-01-02,5,0,0,9664,144

表: https://i.ibb.co/kVZTyt5/ob.jpg

到目前为止我试过这个:

SELECT date, abtest_id, impressions, clicks FROM table1 WHERE variant_id IS NOT NULL
GROUP BY date, abtest_id;

这是结果:

2018-01-01 2 5454 11

2018-01-01 5 76675 5454

2018-01-02 2 7834 99

2018-01-02 5 776 12

我不知道如何将更多的点击次数和展示次数添加到同一行的结果中,并且查看问题中的示例,我不明白其中一些值的存在方式和原因。任何帮助将不胜感激。

谢谢!

最佳答案

对我来说,您不需要向表格中添加列或行。 您需要选择数据,并对某些字段进行一些求和。

我会在 MySQL 中按照这些行做一些事情(仅关闭 full group by 模式):

SELECT t.*,
SUM(CASE 
    WHEN variant_id != 0 THEN impressions 
    ELSE 0 
    END) v_impressions,
SUM(CASE 
    WHEN variant_id != 0 THEN clicks 
    ELSE 0 
    END) v_clicks
FROM `tests` as t
GROUP BY date, abtest_id;

虽然可能有更简单的语法。

这从 variant_id = 0 的行中选择数据,它对 variant_id != 0 的展示次数和点击次数求和,并按日期和 abtest_id 分组。

关于mysql - 如何向 SQL 查询中的列添加值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55984654/

相关文章:

mysql - 添加或更新 MySQL

MySQL 错误 2013

sql - TADOQuery - 编辑模式插入新记录而不是编辑

sql - 如何在 postgres 中显示哈希数组中的键?

sql - TSQL - 表值函数中的 If..Else 语句 - 无法通过

java - com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException : getting a SEVERE: null

php - 通过 mysqli_query() 将长查询传递给 MySQLI

php - MySQL数据库主键使用

sql - 以编程方式添加 SSIS ForEachLoop

sql - 必须声明标量