0

我有一個數據庫表,它看起來像下面所示的總和:SQL查詢來發現與在

Date  Store SubStore ProductsSold 
2013-03-01 A  AA   33 
2013-03-01 B  BB   53 
2013-03-01 C  CC   43 
2013-03-01 B  BB   11 
2013-03-01 A  AA   65 
2013-03-01 A  DD   65 

該表沒有主鍵或外鍵。

我想爲我的報告寫一個查詢,我希望看到銷售產品 的產品爲AA,CC,並且在3月份的其他產品下全部使用。

事情是這樣的:

Substore ProductsSold 
AA    343 
CC    332 
Others   3432 

有沒有一種方法,我能做到嗎?

我想出了一個查詢是這樣的:

Select SubStore, Sum(NumberOfProducts) as Sales 
from 
[dbo].[TableName] 
where [Year] = year(@ParamDate) AND [Month] = month(@ParamDate) 
and (SubStore = 'AA' or SubStore = 'BB') 

請讓我知道什麼樣的變化,我可以做這樣我也可以看到其他..

回答

1

可以使用case來創建商店名稱,你可以組一個值:

select 
    case when Substore in ('AA','CC') then Substore else 'Others' end as SubStore, 
    Sum(ProductsSold) as ProductsSold 
from 
    [dbo].[TableName] 
where 
    [Year] = year(@ParamDate) AND [Month] = month(@ParamDate) 
group by 
    case when Substore in ('AA','CC') then Substore else 'Others' end 
0

最簡單的事情,我能想到的 -

select t.substore, 
SUM(productsSold) as productsSold 
from tablename as t 
where t.substore in ('AA', 'CC') 
group by substore 
UNION ALL 
select 'Others' as substore, 
SUM(productsSold) as productsSold 
from tablename as t 
where t.substore not in ('AA', 'CC')