多个查询到一个(报告)?

时间:2011-04-28 14:45:42

标签: mysql sql database

如何将多个查询合并为一个?

例如:

//Successful Sales:
SELECT username, count(*) as TotalSales, sum(point) as Points FROM sales where submit_date >= 1301612400 AND submit_date <= 1304204400 AND status = 1 group by username

/Return Sales:
SELECT username, count(*) as Return FROM sales where submit_date >= 1301612400 AND submit_date <= 1304204400 AND status = 2 group by username

//Unsuccessful Sales:
SELECT username, count(*) as UnsuccessfulSales FROM sales where submit_date >= 1301612400 AND submit_date <= 1304204400  AND (status = 3 OR status = 6) group by username

所以报告看起来像这样: enter image description here

另外如何添加回报百分比?

注意:修复了SQL查询

我试过这样做但是无法让它起作用?

SELECT username,  TotalSales, Points, Return
     FROM (
      SELECT username, count(*) as TotalSales, sum(point) as Points FROM sales where submit_date >= 1301612400 AND submit_date <= 1304204400 AND status = 1 group by username
      UNION
      SELECT count(*) as Return FROM sales where submit_date >= 1301612400 AND submit_date <= 1304204400 AND status = 4 group by username
    )

...

  //  Example Data Structure 

        CREATE TABLE IF NOT EXISTS `sales2` (
          `salesid` int(11) NOT NULL AUTO_INCREMENT,
          `username` varchar(50) NOT NULL,
          `point` int(11) NOT NULL,
          `status` int(11) NOT NULL,
          PRIMARY KEY (`salesid`)
        ) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;

        INSERT INTO `sales2` (`salesid`, `username`, `point`, `status`) VALUES
        (1, 'User1', 2, 1),
        (2, 'User1', 2, 1),
        (3, 'User2', 11, 1),
        (4, 'User2', 1, 2),
        (5, 'User3', 5, 6);

字段状态= 1,成功销售和展示点

状态2 - 退货销售

状态3/6 - 销售不成功:

2 个答案:

答案 0 :(得分:1)

如果查询中列的数量(和类型)匹配,则可以使用UNION组合3个查询的结果。

答案 1 :(得分:1)

更新: 对于你的第一个问题,我认为这将做你想要的(但是要注意,这个查询很慢,充满了表扫描......你应该要求更有经验的堆栈溢出用户为你优化):

SELECT 
   distinct(outer_sales.username), 
   (SELECT count(*) as Points FROM sales where status = 1 AND username = outer_sales.username) as TotalSales,
   (SELECT sum(point) as Points FROM sales where status = 1 AND username = outer_sales.username) as Points,
   (SELECT count(*) FROM sales where status = 2 AND username = outer_sales.username) as Return,
   (SELECT count(*) FROM sales where (status = 3 OR status = 6) AND username = outer_sales.username) as UnsuccessfulSales
FROM 
   sales outer_sales
ORDER BY
   outer_sales.username;

对于第二个问题,如果您只想在Return列中添加百分号,则可以使用CONCAT函数:http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_concat

尝试:

SELECT CONCAT(CAST(COUNT(*) AS CHAR), '%') AS Return ...