SQL Server

时间:2016-09-22 13:42:11

标签: sql sql-server

我想使用Microsoft SQL Server Management Studio从数据库中获取一些数据。我想做一些计算:

每天我有2个不同的数据点。我想要的是添加一个新的数据点,它是两个数据点的总和。

在我的示例中,我想编写以下任务:

每个'日期'我想要一个新的数据点(让我们称之为category3),这是总和af'数据'来自' category1'和'类别2'。我的代码:

 SELECT   
     [Date], [category], [Data]
 FROM 
     [ ... ]
 WHERE 
     category IN ('category1', 'category2')
 ORDER BY
     AsOfDate 

3 个答案:

答案 0 :(得分:1)

使用UNION ALL

SELECT  [Date],
        [category],
        [Data]
FROM [ ... ]
WHERE category  IN ('category1','category2')
UNION ALL
SELECT  [Date],
        'category3',
        SUM([Data])
FROM [ ... ]
WHERE category  IN ('category1','category2')
GROUP BY [Date];

答案 1 :(得分:0)

您是否只想要一个group by的简单where查询?

 select [Date], SUM(Data)
 from [ ... ]
 Where category  in ('category1','category2')
 group by AsOfDate 

答案 2 :(得分:0)

 SELECT t1.[Date],
        t1.[Data], 
        t2.[Data],
        t1.[Data] + t2.[Data] as [category3]
 FROM [ ... ] t1 inner join [ ... ] t2 on t1.[Date] = t2.[Date] and t1.category = 'category1' and t2.category = 'category2'
 order by AsOfDate