SQL多个where和fields

时间:2013-08-29 09:23:34

标签: mysql sql

我目前在2个表格中组织数据:

会议
meet_id
meet_category

订单
ORDER_ID
meet_id
order_date

我需要编写一个查询,返回会议总数,“长”类别的会议数和“短”类别的会议数。 只计算2011年3月1日之后至少有一个order_date的会议。

输出应该是3个字段和1行

到目前为止,我所拥有的是:

SELECT COUNT(m.meet_id),
COUNT(SELECT m.meet_id WHERE m.meet_category = 'long'),
COUNT(SELECT m.meet_id WHERE m.meet_category = 'short')
FROM Meetings m
INNER JOIN Orders o
ON m.meet_id = o.meet_id 
WHERE o.order_date >= '2011-03-01'; 

这是首先想到的,但这个查询不起作用,我甚至不确定我的方法是否正确。所有帮助赞赏!

3 个答案:

答案 0 :(得分:1)

试试这个:

SELECT COUNT(m.meet_id),
SUM(CASE WHEN m.meet_category = 'long' THEN 1 ELSE 0 END),
SUM(CASE WHEN m.meet_category = 'short' THEN 1 ELSE 0 END)
FROM Meetings m where  meet_id in 
    (select meet_id
    FROM Orders o
    WHERE o.order_date >= '2011-03-01'); 

答案 1 :(得分:0)

试试这个

select count(1) as total_count,innerqry.*

(
select count(m.meet_id), meet_catagory
Meetings m
INNER JOIN Orders o
ON m.meet_id = o.meet_id 
and m.meet_id in 
(select meet_id from orders where order_date>= '2011-03-01')

group by meet_category
) innerqry

如果您只想要一行并且几乎没有已知的会议类型,请尝试使用

SELECT COUNT(m.meet_id),
SUM(CASE WHEN m.meet_category = 'long' THEN 1 ELSE 0 END),
SUM(CASE WHEN m.meet_category = 'short' THEN 1 ELSE 0 END)
FROM Meetings m
INNER JOIN Orders o
ON m.meet_id = o.meet_id 
WHERE  m.meet_id in 
(select meet_id from orders where order_date>'2011-03-01')

答案 2 :(得分:0)

试试这个:

SELECT COUNT(m.meet_id),
(select count(*) from meetings m2 join orders o2 on o2.meet_id = m2.meet_id where m2.meet_category = 'long' and o2.order_date >= '2011-03-01'),
(select count(*) from meetings m2 join orders o2 on o2.meet_id = m2.meet_id where m2.meet_category = 'short' and o2.order_date >= '2011-03-01')
FROM mettings m
INNER JOIN Orders o
ON m.meet_id = o.meet_id
WHERE o.order_date >= '2011-03-01';

您必须实现两个独立的子查询,因为您希望主查询中的总数不按meet_id分组,因此,如果您尝试将子查询与主查询中的字段链接,则会出现按字段分组的错误。