如何为此方案编写SQL

时间:2011-07-03 11:39:56

标签: sql

让我们考虑一下Northwind数据库中的订单表,我需要在一个查询中获取1997和1998年的订单记录数,我该怎么做?

我试过这样的事......

select COUNT(o.orderid) as 'Count Of Orders 1997', COUNT(o1.orderid) as 'Count Of Orders 1998'
from orders O
inner join orders o1
on o.orderid = o1.orderid
where year(o.orderdate) = 1997
or year(o1.orderdate) = 1998

请帮助我...

3 个答案:

答案 0 :(得分:2)

select COUNT(o.orderid) as 'Count Of years'
from orders O   
where year(o.orderdate) = 1997
or year(o1.orderdate) = 1998 
group by year(o.orderdate)

答案 1 :(得分:0)

SELECT 
    (SELECT COUNT(*) FROM orders WHERE YEAR(orderdate) = 1997)
    AS [Orders 1997],
    (SELECT COUNT(*) FROM orders WHERE YEAR(orderdate) = 1998)
    AS [Orders 1998]    

答案 2 :(得分:0)

如果你想要在一行中,那么你也可以使用枢轴功能

with pivot_table as
(
select orderid, orderdate from orders 
)
select * from pivot_table 
pivot ( count(orderid) as 'count' for to_char(orderdate,'YYYY') in ('1997' , '1998') )

然后它将提供类似

的输出
  1997_count   |   1998_count
<count of 1997>   <count of 1998>

或者您可以执行以下操作来获取不同行的输出

  SELECT  to_char(o.OrderDate,'YYYY'), COUNT(o.OrderId) 
    FROM  Orders o
   WHERE  to_char(o.OrderDate,'YYYY') = '1997'  
      or  to_char(o.OrderDate,'YYYY')  = '1998' 
GROUP BY  to_char(o.OrderDate,'YYYY')