SQL - 将select语句中具有不同列数的两个查询合并为一个

时间:2016-03-08 07:36:42

标签: mysql sql

以下是两个单独运行时按预期工作的SQL查询。我已经尝试用UNION& UNION ALL但显然由于每个列返回的列数不同,我无法使用这些技术。

我使用的数据是here

以下是我正在尝试合并的两个单独查询

QUERY ONE

SET group_concat_max_len = 100485760;           
SELECT
    CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(NUM_PRODS ORDER BY NUM_PRODS SEPARATOR ','),',', 50/100 * COUNT(*) + 1),',', -1) AS DECIMAL) AS aa
    ,CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(NUM_PRODS ORDER BY NUM_PRODS SEPARATOR ','),',', 75/100 * COUNT(*) + 1),',', -1) AS DECIMAL) AS bb
    ,CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(NUM_PRODS ORDER BY NUM_PRODS SEPARATOR ','),',', 85/100 * COUNT(*) + 1),',', -1) AS DECIMAL) AS cc
    ,CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(NUM_PRODS ORDER BY NUM_PRODS SEPARATOR ','),',', 95/100 * COUNT(*) + 1),',', -1) AS DECIMAL) AS dd
    ,MAX(NUM_PRODS) AS MAAX 
FROM 
    SALES_INFO

QUERY TWO

SET group_concat_max_len = 100485760;   
SELECT
    CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(NUM_PRODS ORDER BY NUM_PRODS SEPARATOR ','),',', 75/100 * COUNT(*) + 1),',', -1) AS DECIMAL) AS ee
FROM 
    SALES_INFO
WHERE
        SALE_DATE >= DATE_SUB(curdate(), INTERVAL 2 WEEK)

我可以请求帮助将这两个查询合并为一个吗?

1 个答案:

答案 0 :(得分:1)

您可以在select中使用子查询,如下所示:

SELECT CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(NUM_PRODS ORDER BY NUM_PRODS SEPARATOR ','),',', 50/100 * COUNT(*) + 1),',', -1) AS DECIMAL) AS 50per
       ,CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(NUM_PRODS ORDER BY NUM_PRODS SEPARATOR ','),',', 75/100 * COUNT(*) + 1),',', -1) AS DECIMAL) AS 75per
       ,CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(NUM_PRODS ORDER BY NUM_PRODS SEPARATOR ','),',', 85/100 * COUNT(*) + 1),',', -1) AS DECIMAL) AS 85per
       ,CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(NUM_PRODS ORDER BY NUM_PRODS SEPARATOR ','),',', 95/100 * COUNT(*) + 1),',', -1) AS DECIMAL) AS 95per    
       ,MAX(NUM_PRODS) AS MAAX 
       ,(SELECT CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(NUM_PRODS ORDER BY NUM_PRODS SEPARATOR ','),',', 75/100 * COUNT(*) + 1),',', -1) AS DECIMAL) AS 2weeks
         FROM SALES_INFO
         WHERE SALE_DATE >= DATE_SUB(curdate(), INTERVAL 2 WEEK)
         ORDER BY 2weeks limit 1) as 2weeks
FROM 
    SALES_INFO

您没有指定这两个查询与其数据结构之间的关系,所以现在它仅限于第一个结果,如果这不是您需要的,请更新您的要求并且我会更新答案