sql server查询到组记录

时间:2011-05-09 20:36:45

标签: vb.net sql-server-2008

我想从下表中选择:

PostTable

feed     dateinserted        count
  box1       2011-05-28 11:00    1000
  box2 
  box3
  box4 
  box5
  box6

前一天的记录总数,即1,3和5,即 我需要根据我需要的东西来选择我需要检索的总数,例如它可以是box4和方框5 ......不是特别奇怪甚至......我希望这会让它更清晰......

我对所有记录的所有内容:

select sum(count) as [total] from PostTable where Cast(dateinserted as DATE) = 
 CAST(getdate()-1 as DATE)

3 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

SELECT SUM(count) AS Total FROM PostTable WHERE CONVERT(date, dateinserted, 101)=CONVERT(DATE, DATEADD(DAY, -1, GETDATE()), 101) AND feed % 2=1

编辑后,查询将如下所示:

;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

请注意WITH语句开头的分号。查询必须成功运行。

答案 2 :(得分:0)

对于随机奇数

,这可能对您有所帮助

<强> ID阿略 1 2 3 4 五 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