Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
626 views
in Technique[技术] by (71.8m points)

sql - MySQL using Sum and Case

I'm trying to create a GridView with ASP.NET connecting to a MySQL database. The data appears like below.

BusinessUnit    OrderDate      Canceled
UnitA           1/15/2013          N
UnitA           10/1/2013          N
UnitB           10/15/2013         N
UnitB           10/22/2013         N
UnitB           10/22/2013         N

Based on the records above, I'd like the result to appear like below

BusinessUnit  TodaysOrders   ThisMonthsOrders  ThisYearsOrders
UnitA              0                1                2
UnitB              2                3                3

My current code is below. It's giving me error (something about DatabaseName.sum does not exist. Check the Function Name Parsing and Resolution' section... )

Select  
    SUM (CASE WHEN (OrderDate)=DATE(NOW()) THEN 1 ELSE 0 END) AS TodaysOrders,
    SUM (CASE WHEN YEAR(OrderDate) = YEAR(CURDATE()) AND MONTH(OrderDate) = MONTH(CURDATE()) THEN 1 ELSE 0 END) AS ThisMonthsOrders,
    SUM (CASE WHEN YEAR(main_order_managers.creation_date) = YEAR(CURDATE()) THEN 1 ELSE 0 END) AS ThisYearsOrders 

code continues

FROM OrderTable WHERE OrderTable.Canceled. <> 'Y';

Is Sum Case the best use here?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The error is caused by the space between function name and parenthesis

SUM (CASE WHEN ...
   ^^

Read more Function Name Parsing and Resolution

Try

SELECT BusinessUnit,
       SUM(CASE WHEN OrderDate = CURDATE() THEN 1 ELSE 0 END) TodaysOrders,
       SUM(CASE WHEN DATE_FORMAT(OrderDate, '%Y%m') = DATE_FORMAT(CURDATE(), '%Y%m') THEN 1 ELSE 0 END) ThisMonthsOrders,
       SUM(CASE WHEN YEAR(OrderDate) = YEAR(CURDATE()) THEN 1 ELSE 0 END) ThisYearsOrders
  FROM OrderTable
 WHERE Canceled <> 'Y'
 GROUP BY BusinessUnit

Here is SQLFiddle demo


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...