T-SQL select语句... SUM和HAVING问题

时间:2013-08-09 18:11:55

标签: sql-server tsql

我有一张类似下面的表......

我需要添加具有完全相同日期的每一行的值。 (例如前两行将等于'5',接下来的两行,'5',接下来的两行,'8')

StoretCode   LocName    ParName   DateTime       Value
95010-A-9    AB 901_4   On Line   201305160000   1
NULL         AB 905_8   On Line   201305160000   4
95010-A-9    AB 901_4   On Line   201305170000   2
NULL         AB 905_8   On Line   201305170000   3
95010-A-9    AB 901_4   On Line   201305180000   4
NULL         AB 905_8   On Line   201305180000   4  

结果还应该有一个新的LocName ...所以它应该看起来像......

StoretCode   LocName  ParName  DateTime      Value
95010-A-9    AERBAS   On Line  201305160000  5
95010-A-9    AERBAS   On Line  201305170000  5
95010-A-9    AERBAS   On Line  201305180000  8

我试过......

Select 'AB 901_4','AB 905_8', Sum(Value)
from dbo.DATA  

但结果如预期的那样......一行总计所有行......

也试过.....

Select 'AB 901_4','AB 905_8', Sum(Value)
from dbo.DATA
Where LocName, DateTime = LocName, DateTime

但结果是......

  

Msg 4145,Level 15,State 1,Line 3
  在预期条件的上下文中指定的非布尔类型的表达式,靠近','。

尝试了其他几个但结果类似于上面的非布尔消息...

2 个答案:

答案 0 :(得分:1)

Select StoretCode , 'AERBAS' as LocName , ParName , DATA.DateTime, datecount.count as [value]
from dbo.DATA 
join ( select DateTime, count(*) as count from dbo.DATA group by DateTime ) datecount 
  on data.DateTime = datecount.DateTime 
where date.StoretCode is not null  

如果你想要LocName的硬编码值,那么'LocName'

答案 1 :(得分:1)

也许是这些方面的东西?

Select 
  max(StoretCode), 
  'AERBAS' as Locname, 
  max(ParName), 
  DateTime, 
  Sum(Value)
from dbo.DATA
group by DateTime
order by DateTime