结果显示两行到一行

时间:2014-04-07 22:58:08

标签: sql sql-server tsql

我写了一个查询来计算每天的正面和负面结果。我的问题是,每个postivie我得到两行到负面日。

  • 我希望每天有一行带有正负列(无多天)。

enter image description here

SELECT case([MsrSplatPositive]) when '0' then count([MsrSplatPositive]) end as 'Negative'
,case([MsrSplatPositive]) when '1' then count([MsrSplatPositive]) end as 'Positive'
,CONVERT(VARCHAR(10), f.NewsDate, 106) as 'Date'
 FROM [News].[dbo].[Score] s
inner join [News].[dbo].[Feed] f
on f.ScoreId = s.Id
where f.NewsDate between dateadd(day,-30,GETDATE()) and GETDATE()
group by [MsrSplatPositive],CONVERT(VARCHAR(10), f.NewsDate, 106)

2 个答案:

答案 0 :(得分:4)

从GROUP BY中删除MsrSplatPositive。

这迫使积极和消极的结果进入不同的日子。

然后使用SUM(CASE ...)代替CASE(COUNT ...)

你在SELECT中有这个:

case([MsrSplatPositive]) when '0' then count([MsrSplatPositive]) end as 'Negative'

反而想要这个:

sum(CASE WHEN MsrSplatPositive = 0 THEN 1 ELSE 0 END) as 'Negative'

编辑:

所有修正应该是这样的:

SELECT SUM(CASE WHEN MsrSplatPositive = 0 THEN 1 ELSE 0 END) 'Negative'
      ,SUM(MsrSplatPositive 'Positive'
      ,CONVERT(VARCHAR(10), f.NewsDate, 106) as 'Date'
  FROM News.dbo.Score s
       INNER JOIN 
       News.dbo.Feed f on f.ScoreId = s.Id
 WHERE f.NewsDate BETWEEN DATEADD(DAY,-30,GETDATE()) and GETDATE()
 GROUP BY f.NewsDate

答案 1 :(得分:0)

试试这个......我没有运行查询,但认为这应该可以达到结果。我已将原始查询修改为在正负列中返回0而不是null。然后使用修改后的SQL作为临时表,并按日期值进行分组。

Select Sum(Temp.Negative), Sum(Temp.Positive), Temp.Date From
(
SELECT case([MsrSplatPositive]) when '0' then count([MsrSplatPositive]) 
    else 0 end as 'Negative'
,case([MsrSplatPositive]) when '1' then count([MsrSplatPositive] 
    else 0) end as 'Positive'
,CONVERT(VARCHAR(10), f.NewsDate, 106) as 'Date'
FROM [News].[dbo].[Score] s
inner join [News].[dbo].[Feed] f
on f.ScoreId = s.Id
where f.NewsDate between dateadd(day,-30,GETDATE()) and GETDATE()
group by [MsrSplatPositive],CONVERT(VARCHAR(10), f.NewsDate, 106)
) Temp
Group By Temp.Date

希望这有帮助。