日期:2014-05-17  浏览次数:20716 次

【急求】求教SQL语句时间查询问题
SQL code
SELECT SUM(TotalPrice) FROM NarukoEC.dbo.Orders AS o
WHERE  CreateTime BETWEEN '20110101' AND '20110131' AND o.TotalGoodsPrice>0 
AND 
 NOT EXISTS(
SELECT 1 FROM NarukoEC.dbo.Orders WHERE state not in(0,5,7) AND  CreateTime < '20110101' AND CustomerID = o.CustomerID
)


SQL code
SELECT SUM(TotalPrice) FROM NarukoEC.dbo.Orders AS o
WHERE  CreateTime BETWEEN '20110201' AND '20110228' AND o.TotalGoodsPrice>0 
AND 
 NOT EXISTS(
SELECT 1 FROM NarukoEC.dbo.Orders WHERE state not in(0,5,7) AND  CreateTime < '20110201' AND CustomerID = o.CustomerID
)



我要依次查询 二零零一年一月份 到 十二月份每个月的数据,这样写的话就每次都要改动月份!
如何让它一次性就全部查询出来?

------解决方案--------------------
SQL code
SELECT  SUBSTRING(CreateTime,5,2),SUM(TotalPrice)
FROM    NarukoEC.dbo.Orders AS o
WHERE   o.TotalGoodsPrice > 0 AND [state] IN ( 0, 5, 7 )
GROUP BY SUBSTRING(CreateTime,5,2)

------解决方案--------------------
SQL code
SELECT  DATEPART(mm , CreateTime) AS 月份 , SUM(TotalPrice) AS 合计
FROM    NarukoEC.dbo.Orders AS o
WHERE   CreateTime BETWEEN '20110101' AND '20111231'
        AND o.TotalGoodsPrice > 0
        AND state NOT IN (0 , 5 , 7)
GROUP BY DATEPART(mm , CreateTime)