sql server query to group records
i would like to select from the following table:
PostTable
feed dateinserted开发者_StackOverflow中文版 count
box1 2011-05-28 11:00 1000
box2
box3
box4
box5
box6
the total number of records for the previous day where the feed is, 1, 3 and 5 i.e. the feeds I need to retrieve totals for will just be selected based on what I need for instance it could be box4 and box 5...not specifically odd and even...I hope this makes it more clearer..
what I have for all records:
select sum(count) as [total] from PostTable where Cast(dateinserted as DATE) =
CAST(getdate()-1 as DATE)
SELECT feed, SUM(count) AS total FROM PostTable
WHERE Cast(dateinserted as DATE) = CAST(getdate()-1 as DATE) AND feed IN ('box1', 'box3', 'box4')
GROUP BY feed
SELECT SUM(count) AS Total FROM PostTable WHERE CONVERT(date, dateinserted, 101)=CONVERT(DATE, DATEADD(DAY, -1, GETDATE()), 101) AND feed % 2=1
After your edit the query would look something like this:
;with temp as(
select ROW_NUMBER() OVER (ORDER BY feed) AS RowNum, * from PostTable)
SELECT SUM(count) AS Total FROM temp WHERE CONVERT(date, dateinserted, 101)=CONVERT(DATE, DATEADD(DAY, -1, GETDATE()), 101) AND RowNum % 2=1
Please note the semicolon in the begining of WITH statement. it is necessary for the query to run successfully.
This may be help full to you for random odd number
id阿略 1 2 3 4 5 6 7 8 9
declare @input varchar(10)
set @input = 1
while @input < = 9
begin
select id from emp where id = @input
set @input = @input + 2
end
精彩评论