当值等于设定值时,列的总和

时间:2017-06-26 21:22:41

标签: sql sql-server sql-server-2008

我正在尝试获取列的总和,其中另一列值等于某些值,这就是我现在的工作方式

SELECT [Date]= CONVERT(char(10), CURRENT_TIMESTAMP, 103), Items = SUM(NumberOfItems), WorkstationID 
FROM [DB].[DB].[dbo].[SortStatistics]
WHERE RecordedPeriod Between '06/23/17 01:00:00AM' and '06/23/17 23:59:00PM' AND WorkstationID = 'D11' 
GROUP BY WorkstationID
SELECT [Date]= CONVERT(char(10), CURRENT_TIMESTAMP, 103), Items = SUM(NumberOfItems), WorkstationID 
FROM [DB].[DB].[dbo].[SortStatistics]
WHERE RecordedPeriod Between '06/23/17 01:00:00AM' and '06/23/17 23:59:00PM' AND WorkstationID = 'D12' 
GROUP BY WorkstationID
SELECT [Date]= CONVERT(char(10), CURRENT_TIMESTAMP, 103), Items = SUM(NumberOfItems), WorkstationID 
FROM [DB].[DB].[dbo].[SortStatistics]
WHERE RecordedPeriod Between '06/23/17 01:00:00AM' and '06/23/17 23:59:00PM' AND WorkstationID = 'D13' 
GROUP BY WorkstationID

这是我的结果

 Date       Items   WorkstationID
 26/06/2017 14886   D11

 Date       Items   WorkstationID
 26/06/2017 12973   D12

 Date       Items   WorkstationID
 26/06/2017 12124   D13

我希望将此视为结果

 Date       Items   Sorter
 26/06/2017 39983   DUAL    

列数据类型如下

Items, INT
WorkstationID, Varchar(4)

1 个答案:

答案 0 :(得分:2)

目前还不清楚您希望'DUAL'来自哪里,但您可以只使用一个查询:

SELECT [Date] = CONVERT(char(10), CURRENT_TIMESTAMP, 103),
       Items = SUM(NumberOfItems),
       'DUAL' as Sorter 
FROM [DB].[DB].[dbo].[SortStatistics]
WHERE RecordedPeriod >= '2017-06-23 01:00:00' AND
      RecordedPeriod <  '2017-06-24' AND
      WorkstationID IN ('D11', 'D12', 'D13')