我有两个来自同一个表的MySQL语句:
GetSpectrumData
第二个陈述是:
GetOutputData
我想要的结果是这样一个表:
我尝试使用Union但是没有用,因为我有两个不同的列
知道如何获得第3张桌子吗?
答案 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
CASE
语句