仅在别名中对多个列进行分组

时间:2015-09-05 22:53:32

标签: mysql sql

我需要价值' table_index'和'利润'只是一个别名

我的SQL代码是:

SELECT 
receipt.*,     
customer.name, 
input_product.table_index AS table_index,      
input_service.table_index AS table_index,      
input_other.table_index AS table_index,
output_product.table_index AS table_index,     
output_service.table_index AS table_index,     
output_other.table_index AS table_index,
(SELECT COUNT(id) FROM receipt_itens WHERE receipt_itens.receipt = receipt.id) AS total_iten,
(SELECT SUM(VALUE) FROM input_product WHERE input_product.id = receipt_itens.in_product)  AS profit,
(SELECT SUM(VALUE) FROM input_service WHERE input_service.id = receipt_itens.in_service)  AS profit,
(SELECT SUM(VALUE) FROM input_other WHERE input_other.id = receipt_itens.in_other)  AS profit,
(SELECT SUM(VALUE) FROM output_product WHERE output_product.id = receipt_itens.ou_product)  AS profit,
(SELECT SUM(VALUE) FROM output_service WHERE output_service.id = receipt_itens.ou_service)  AS profit,
(SELECT SUM(VALUE) FROM output_other WHERE output_other.id = receipt_itens.ou_other)  AS profit

FROM    receipt

LEFT JOIN       receipt_itens ON receipt.`id` = receipt_itens.`receipt`
LEFT JOIN       input_product ON receipt_itens.`in_product` = input_product.`id`
LEFT JOIN       input_service ON receipt_itens.`in_service` = input_service.`id`
LEFT JOIN       input_other ON receipt_itens.`in_other` = input_other.`id`
LEFT JOIN       output_product ON receipt_itens.`ou_product` = output_product.`id`
LEFT JOIN       output_service ON receipt_itens.`ou_service` = output_service.`id`
LEFT JOIN       output_other ON receipt_itens.`ou_other` = output_other.`id`
LEFT JOIN       customer ON customer.`id` = output_service.`customer` OR
output_service.`customer` OR output_product.`customer` OR
input_product.`customer` OR
input_service.`customer`

WHERE   (              
    receipt.id LIKE "%%" OR            
    customer.name LIKE "%%"    
)

ORDER BY created DESC
LIMIT   0, 10

带有重复列的结果

enter image description here

我只需要忽略那些毫无价值的重复列,我尝试使用 GROUP BY ,但它不起作用

1 个答案:

答案 0 :(得分:1)

您可以尝试使用" CASE"在查询的选择部分。像:

CASE
        WHEN input_product.table_index IS NOT NULL THEN input_product.table_index 
        WHEN input_service.table_index IS NOT NULL THEN input_service.table_index 
        ....
        ELSE NULL
    END AS table_index,

同样的利润。