SqlClient按日期计算

时间:2014-11-27 16:56:14

标签: c# sql sql-server

我无法向谷歌阐述我的问题,以了解如何做到这一点,我希望有人会帮助我。

这是我的出发点。

SqlCommand command = new SqlCommand("SELECT BOOK_ID, BOOK_DATE, Sum(BOOK_COUNT) " +
                                    "FROM BOOKS " +
                                    "WHERE (BOOK_ID = '1' OR " +
                                           "BOOK_ID = '2' OR " +
                                           "BOOK_ID = '3' )  " +
                                    "AND STATUS  = '0'    " +
                                    "GROUP BY BOOK_ID, BOOK_DATE ", cn);

SqlDataReader reader = command.ExecuteReader();

while (reader.Read())
{
    int id = (int)reader[0]; 
    DateTime date = (DateTime)reader[1]; 
    int count = (int)reader[2];

    if (id == 1)
    {
       /*...*/
    }

    if (id == 2)
    {
       /*...*/
    }

    if (id == 3)
    {
       /*...*/
    }
 }

 reader.Close();

DBSCA

DBSCA

我想按日期排序,如果日期和ID相同,那么获取书籍的数量...... 像这样:

BOOK_DATE  BOOK_ID  BOOK_COUNT  
2014.11.17     1        1         
2014.11.21     2        1           
2014.11.25     2        2           
2014.11.26     1        2           
2014.11.26     3        2           
2014.11.27     3        1           
2014.11.28     3        1           

谢谢,如果有人可以帮助我,我为糟糕的英语道歉!

4 个答案:

答案 0 :(得分:1)

ORDER BY DATEADD(DAY, 0, DATEDIFF(DAY, 0, BOOK_DATE)), Sum(BOOK_COUNT)

DATEADD(dd,0,DATEDIFF(DAY,0,BOOK_DATE))仅获取记录的日期参与者。你还需要使用这个功能进行分组。

感谢@marc_s

的建议

答案 1 :(得分:1)

这个。 ConvertBOOK_DATE Date然后在Group by

中使用它
SELECT BOOK_ID,
       CONVERT(DATE, BOOK_DATE),
       Sum(BOOK_COUNT)
FROM   BOOKS
WHERE   BOOK_ID IN (1,2,3)
       AND STATUS = 0
GROUP  BY BOOK_ID,
          CONVERT(DATE, BOOK_DATE) 

答案 2 :(得分:1)

Group by日期时间字段的日期部分:

SqlCommand command = new SqlCommand("SELECT BOOK_ID, DATEADD(DAY, 0, DATEDIFF(DAY, 0, BOOK_DATE)), Sum(BOOK_COUNT) " +
                                    "FROM BOOKS " +
                                    "WHERE (BOOK_ID = '1' OR " +
                                           "BOOK_ID = '2' OR " +
                                           "BOOK_ID = '3' )  " +
                                    "AND STATUS  = '0'    " +
                                    "GROUP BY BOOK_ID, DATEADD(DAY, 0, DATEDIFF(DAY, 0, BOOK_DATE)) 
ORDER BY 2", cn);

答案 3 :(得分:0)

要按结果集中的第二个值排序,只需添加ORDER BY 2

即可
SqlCommand command = new SqlCommand("SELECT BOOK_ID, BOOK_DATE, Sum(BOOK_COUNT) " +
                                    "FROM BOOKS " +
                                    "WHERE (BOOK_ID = '1' OR " +
                                           "BOOK_ID = '2' OR " +
                                           "BOOK_ID = '3' )  " +
                                    "AND STATUS  = '0'    " +
                                    "GROUP BY BOOK_ID, BOOK_DATE 
ORDER BY 2", cn);