SQL从一个表中获取计数并拆分为两列

时间:2015-11-16 14:43:21

标签: sql sql-server

我有一张这样的表:

Date        Product
1/1/2015    Apples
1/1/2015    Apples
1/1/2015    Oranges
1/2/2015    Apples
1/2/2015    Apples
1/2/2015    Oranges

我如何做一个选择,所以我得到这样的东西:

Date      Count of Apples    Count of Oranges
1/1/2015      2                 1
1/2/2015      2                 1

感谢。我已经尝试了这样的情况,但错误被抛出:

Select 'Date',
CASE WHEN 'Product' = 'Apples' THEN COUNT(*) ELSE 0 END as 'Count'
FROM #TEMP Group by 1,2

每个GROUP BY表达式必须至少包含一个不是外部引用的列。

3 个答案:

答案 0 :(得分:3)

您可以像这样进行条件聚合:

select 
  [date], 
  sum(case when Product = 'Apples'  then 1 else 0 end) as [Count of Apples],
  sum(case when Product = 'Oranges' then 1 else 0 end) as [Count of Oranges]
from #temp
group by [date]

答案 1 :(得分:1)

使用条件聚合:

select date, 
       sum(case when Product = 'Apples' then 1 else 0 end) as Apples,
       sum(case when Product = 'Oranges' then 1 else 0 end) as Oranges,
from table
group by date

答案 2 :(得分:1)

SQL Server不接受GROUP BY中的列引用。所以," 1"和" 2"请参阅第一和第二号。

但是,您似乎混淆了字符串常量和列。仅对字符串和日期常量使用单引号。我怀疑DateProduct是列的名称。因此,您可能想要的查询是条件聚合:

Select Date,
       SUM(CASE WHEN Product = 'Apples' THEN 1 ELSE 0 END) as NumApples
FROM #TEMP
Group by Date
Order by Date;