两个MYSQL语句具有不同的列名但来自同一个表

时间:2017-12-16 07:06:24

标签: mysql

我有两个来自同一个表的MySQL语句:

GetSpectrumData

enter image description here

第二个陈述是:

GetOutputData

enter image description here

我想要的结果是这样一个表:

enter image description here

我尝试使用Union但是没有用,因为我有两个不同的列

知道如何获得第3张桌子吗?

2 个答案:

答案 0 :(得分:1)

使用条件聚合:

SELECT
    product_id,
    COUNT(DISTINCT CASE WHEN status = 1 AND ispaid != 2
                        THEN user_id ELSE NULL END) AS NonebuyersNumber
    COUNT(DISTINCT CASE WHEN ispaid = 1 THEN user_id ELSE NULL END) AS BuyersNumber
FROM table1
WHERE
    (status = 1 AND ispaid != 2) OR 
    ispaid = 1
GROUP BY
    product_id;

这应该有效,因为您的两个查询都聚合在product_id上,唯一的区别是WHERE子句。我们可以合并两个查询中的记录,然后使用CASE表达式来定位每个原始查询的记录。

答案 1 :(得分:0)

SELECT t1.product_id AS product_id
SELECT CASE WHEN t1.NonebuyersNumber IS NULL 
            THEN 0 
            ELSE t1.NonebuyersNumber 
            END 
    AS NonebuyersNumber,
SELECT CASE WHEN t2.BuyersNumber IS NULL 
            THEN 0 
            ELSE t2.BuyersNumber 
            END 
    AS BuyersNumber
FROM
(SELECT 
    `table1`.`product_id` As product_id , 
    COUNT(DISTINCT(table1.user_id)) AS NonebuyersNumber 
    FROM table1 WHERE status =1 
    AND `ispaid` != 2 
    GROUP BY `table1`.`product_id`) 
AS t1
INNER JOIN
(SELECT 
    `table1`.`product_id` As product_id , 
    COUNT(DISTINCT(table1.user_id)) AS BuyersNumber 
    FROM table1 WHERE `ispaid` = 1 
    GROUP BY `table1`.`product_id`) 
AS t2
ON t1.product_id = t2.product_id

基本上,您需要关注

  • 加入product_id
  • 上的观看次数
  • 如果其中一个买方编号为NULL
  • ,请使用CASE语句