mysql - 如何在查询中两次计算相同的值

标签 mysql sql

从下面的查询中得到的结果显然是一个文件,这个文件在 whataver 列中只有 rur,我想有两个条目具有相同的文件,我有兴趣计算两次。 文件名大小类型(这是一个枚举) ABC 10mb rur, 方式

        select filename,,size,type, (case when type like '%rur%' then 'rurroad' when type like '%way%' then 'hway' end) as whatever 
        from files as f,metadata as v where f.id = v.id 
        and filename like 'ANC'
        and type like '%rur%'

我的结果是

         filename   size    type(this is an enum)       whatever
         ABC    10 mb     rur,way                          rur

我想得到

         filename   size    type(this is an enum)       whatever
         ABC    10 mb     rur,way                          rur
         ABC    10 mb     rur,way                          way

同时,我的文件有大小,通常我想知道 rur 有多少 MB,而 way 有多少。我想创建一个数据透视表摘要,这就是为什么我希望它们都在一个 View /表中。所以如果可能的话,我还想获得 10mb rur 和 10mb 方式的大小。否则我可以避免那样计算大小

我想得到结果,因为我有 30% rur 20% way 和 xx% null

最佳答案

只需使用UNION:

select filename, size, type, (case when type like '%rur%' then 'rurroad' when type like '%way%' then 'hway' end) as whatever 
    from files as f, metadata as v where f.id = v.id 
    and filename like 'ANC'
    and type like '%rur%'

union all

select filename, size, type, (case when type like '%rur%' then 'rurroad' when type like '%way%' then 'hway' end) as whatever 
    from files as f, metadata as v where f.id = v.id 
    and filename like 'ANC'
    and type like '%way%' -- here we select %way% records - records with "rur,way" will appear in both queries.

PS:除非MySQL不支持。不确定,但我的猜测是它确实如此,毕竟它是 ANSI SQL。 缴费灵:it does .

关于mysql - 如何在查询中两次计算相同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19184803/

相关文章:

php - mysql 查询遇到困难

mysql - 连接到局域网中另一台 PC 上的 mysql 服务器

php - 在 codeigniter 中组合日期和时间列进行查询

php - 查找两个数据库字段之间的日期

php - 这个分页有什么问题?

mysql - 等待 MySQL 表上的表级锁定

SQL查询优化帮助请

sql - 将smallint 转换为varchar 时的情况

mysql - sql building的进出记录

sql - SQL查询:在主键中查找空白