在SQL中显示每天的产品销售



我有一个问题,我找不到解决方案。

我有一张桌子"卖",所有商店的销售都会出售,我想每天每天的每种产品都有多少销售。

例如:

|       DATE |  NAME    | QTY |
|------------|----------|-----|
| 2014-07-03 |     Coca |   1 |
| 2014-07-03 |    Fanta |   1 |
| 2014-07-03 | Orangina |   5 |
| 2014-07-03 |     Coca |   3 |
| 2014-07-04 |     Coca |   2 |
| 2014-07-05 |     Coca |   4 |
| 2014-07-05 |    Fanta |   1 |
| 2014-07-05 |    Juice |   2 |

我想要的显示是:

    |       NAME | TOTAL  | 2014-07-03 |  2014-07-04 |  2014-07-05 |
    |------------|--------|------------|-------------|-------------|
    |      Coca  |   10   |         4  |          2  |          4  |
    |     Fanta  |    2   |         1  |          0  |          1  |
    |  Orangina  |    1   |         1  |          0  |          0  |
    |     Juice  |    1   |         0  |          0  |          1  |

用户将指定他要显示的期间,因此我必须在日期之间使用两次函数。

我尝试使用枢轴功能,但是我仍然不熟悉它

编辑:我正在使用SQL Server 2012。

非常感谢您的帮助。

Create table temp 
(
tdate date,
name varchar(10),
qty int
)
insert into temp values (getdate(),'A',10)
insert into temp values (getdate(),'B',20)
insert into temp values (getdate(),'C',20)
insert into temp values (getdate(),'A',20)
insert into temp values (getdate(),'B',30)
insert into temp values (getdate(),'C',40)
insert into temp values (getdate()+1,'A',20)
insert into temp values (getdate()+1,'B',30)
insert into temp values (getdate()+1,'C',40)


select * from 
( select tdate, name, qty
  from temp
) src
pivot (
  sum(qty)
  for tdate in ([2015-05-12],[2015-05-13])
) piv;

这不是做技巧吗?

SELECT sum(QTY), DATE, NAME FROM SELLS WHERE DATE BETWEEN .... GROUP BY DATE,NAME

p.s:添加了两句之间

最新更新