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
219 views
in Technique[技术] by (71.8m points)

sql server - SQL query get count item for report per day of the month?

i need sql query for report from table item per day(fix day1-day31 as column) of the month when i input month and year.

This is my table (item)

  ID   |   NAME  |   DATE
---------------------------------------------------
   1   |   ITEM A |   2015-2-25 13:37:49
   2   |   ITEM A |   2015-2-25 14:37:49
   3   |   ITEM A |   2015-2-26 13:30:55
   4   |   ITEM B |   2015-2-26 15:37:49
   5   |   ITEM B |   2015-2-26 17:57:49
   6   |   ITEM C |   2015-2-27 13:00:33


(input month=02 and year=2015)
What I need to achieve with a view is the following:

NAME | 1| 2| 3|…|25|26|27|28|29|30|31|Total
------------------------------------------------------
ITEM A| 0| 0| 0|…| 2 | 1 | 0 | 0 | 0 | 0 | 0 | 3
ITEM B| 0| 0| 0|…| 0 | 2 | 0 | 0 | 0 | 0 | 0 | 2
ITEM C| 0| 0| 0|…| 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1


Any ideas would be very much appreciated.

Thanks in advance.

Sorry this is my first post.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You can do this using a PIVOT in your query

SELECT name, 
       [1], 
       [2], 
       [3], 
       [4], 
       [5],
       [6],
       [7],
       [8],
       [9],
       [10],
       [11],
       [12],
       [13],
       [14],
       [15],
       [16],
       [17],
       [18],
       [19], 
       [20], 
       [21], 
       [22], 
       [23], 
       [24], 
       [25], 
       [26], 
       [27], 
       [28], 
       [29], 
       [30], 
       [31],
       ([1] + [2] + [3] + [4] + [5] + [6] + [7] + [8] + [9] + [10] + [11] + [12] + [13] + [14] + [15] + [16] + [17] + [18] + [19] +  [20] + [21] + [22] + [23] + [24] + [25] + [26] + [27] + [28] + [29] + [30] + [31]) as total
FROM   
(
    SELECT Name, 
        id, 
        Datepart(day, [date]) day 
    FROM   item 
    WHERE  MONTH([date]) = 2 AND YEAR([date]) = 2015
) x 
PIVOT 
(
    count(id) 
    FOR day IN ([1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [17], [18], [19],  [20], [21], [22], [23], [24], [25], [26], [27], [28], [29], [30], [31]) 
) p 

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

...