合并两个SQL查询的结果

时间:2016-06-24 16:38:46

标签: php sql select phpmyadmin union

我想将两个查询的结果合并为一个resulttable,其中包含三列,result1result2dateday,查询是矛盾的

SELECT COUNT( DISTINCT `cust` ) AS result1, DATE( `date` ) AS dateday
FROM `salg_test`
WHERE `saved` =0
AND `is_void` =0
GROUP BY dateday
ORDER BY dateday DESC

SELECT COUNT( DISTINCT `cust` ) AS result2, DATE( `date` ) AS dateday
FROM `salg_test`
WHERE `saved` =1
AND `is_void` =0
GROUP BY dateday
ORDER BY dateday DESC

我希望两个结果按dateday变量分组并排序。

2 个答案:

答案 0 :(得分:2)

应该能够做到这样的事情:

SELECT COUNT( DISTINCT CASE `saved` when 0 then `cust` else null end ) AS result1
, COUNT( DISTINCT CASE `saved` when 1 then `cust` else null end ) AS result2
, DATE( `date` ) AS dateday
FROM `salg_test`
WHERE `is_void` =0
GROUP BY dateday
ORDER BY dateday DESC

答案 1 :(得分:0)

怎么样:

WHERE (`saved`= 1 OR `saved`= 0)

或者,如果saved的唯一可能值为1或0,则只需从查询中省略该条件。