按订单日期和产品SQL Server 2008区分

时间:2012-05-04 19:49:03

标签: linq sql-server-2008

这是我在这里发表的第一篇文章,所以如果我被误认为是我的帖子和英文,我会抱歉:)

我已经在谷歌进行研究,不幸的是直到现在我无法解决这个问题。

这是我的问题,显示每个产品的按日期排序,我希望按产品区分

这是我的查询示例

SELECT Orders.OrderDate
          ,SUM(OrderDetails.OrderDetailQuantity) AS totalOrdered
          ,Products.ProductId 
FROM Orders 
INNER JOIN OrderDetails ON Orders.OrderId = OrderDetails.OrderId 
INNER JOIN Products ON OrderDetails.ProductId = Products.ProductId 
GROUP BY Orders.OrderId
          ,Orders.OrderDate
          ,Products.ProductId 
HAVING (CONVERT(VARCHAR,  Orders.OrderDate, 23) BETWEEN @from AND @to)

现在,我希望根据OrderDate之间的产品区分,我知道这里的大问题是DATE,但我不知道如何通过此查询区分日期。

请帮帮我。谢谢。

P.S。:如果你想在linq表达式中解决这个问题,那将是高度接受的:)

1 个答案:

答案 0 :(得分:1)

样本数据和期望的结果会有所帮助。当你说“与众不同”时,我认为你的意思是分组。注意,在WHERE子句中,如果确保@from&的时间分量,则不需要强制转换Order.OrderDate。 @to params设置正确(包括每一天)。在比较的左侧应用强制转换操作绝对不是一个好主意。

SELECT  --cast(Orders.OrderDate as date),
        Products.ProductId 
        SUM(OrderDetails.OrderDetailQuantity) AS totalOrdered,
FROM Orders 
INNER JOIN OrderDetails ON Orders.OrderId = OrderDetails.OrderId 
INNER JOIN Products ON OrderDetails.ProductId = Products.ProductId 
where Orders.OrderDate between cast(@from as date) AND cast(@to as date)
GROUP 
BY      --cast(Orders.OrderDate as date),
        Products.ProductId 


-- to illustrate:
declare @From datetime = '1/1/2000 10:30:22',
        @To datetime = '1/3/2000 9:11:31'

declare @orders table (i int, dt datetime)
insert into @orders
    values(1, '1/1/2000 8:00'),(2, '1/2/2000 10:00'), (3, '1/4/2000 3:00')


-- only returns i=2
select *
from    @orders
where dt between @From and @To

-- returns i=1 & i=2
select *
from    @orders
where dt between cast(@From as date) and cast(@To as date)