从不同的结果集和不同的条件创建一个表

时间:2011-03-29 10:22:47

标签: mysql sql

如果我有一张桌子(ORDER),请说出来是这样的:

ORDER

typeid  | price  | status | 
  7        8000      3 
  7        8000      3 
  7        8000      3 
  8        8000      3 
  8        8000      8 
  7        8000      8 

我想从上表中得到3个结果:

select count(STATUS) AS TRAFFIC WHERE TYPEID = 7;

sum(price) AS REVENUE, count(STATUS) AS SUBSCRIBER FROM CMSORDER WHERE TYPEID = 7 AND status = 8 ;

上面结合2个代码的语法是什么?所以我可以得到这张表:

traffic  | revenue  | subscriber
  4         8000          1 

有人能帮助我吗?

3 个答案:

答案 0 :(得分:0)

您正在寻找的魔力是GROUP BY子句:

select count(ORDER.STATUS) AS TRAFFIC 
sum(ORDER.price) AS REVENUE, 
count(ORDER.STATUS) AS SUBSCRIBER 
FROM CMSORDER, ORDER 
WHERE CMSORDER.TYPEID = ORDER.TYPEID 
AND CMSORDER.status = 8 
AND ORDER.TYPEID = 7
GROUP BY ORDER.STATUS;

答案 1 :(得分:0)

据我所知,它可以是这样的 -

SELECT count(if(typeid = 7, 1, null)) TRAFFIC,
  sum(if(TYPEID = 7 AND status = 8, price, null)) AS REVENUE,
  count(if(TYPEID = 7 AND status = 8, STATUS, null)) AS SUBSCRIBER
FROM
  CMSORDER

答案 2 :(得分:0)

SELECT
  COUNT(status) AS TRAFFIC,
  SUM  (CASE status WHEN 8 THEN price  END) AS REVENUE,
  COUNT(CASE status WHEN 8 THEN status END) AS SUBSCRIBER
FROM CMSORDER
WHERE typeid = 7