-1

I have two tables:

+-----------+
| Customer  |
+-----------+
| ID | Name |
+----+------+
| 1  | Jack |
+----+------+
| 2  | John |
+----+------+

+----------------------------------------+
|                  Bill                  |
+----------------------------------------+
| ID | Customer_ID | date       | amount |
+----+-------------+------------+--------+
| 1  | 1           | 01.01.2015 | 10$    |
+----+-------------+------------+--------+
| 2  | 1           | 01.01.2014 | 20$    |
+----+-------------+------------+--------+
| 3  | 2           | 01.01.2015 | 5$     |
+----+-------------+------------+--------+
| 4  | 2           | 01.02.2015 | 50$    |
+----+-------------+------------+--------+
| 5  | 2           | 01.01.2014 | 15$    |
+----+-------------+------------+--------+

I need to know the sum of all the bills a customer got in a year.

That's pretty easy:

SELECT 
    SUM(Bill.amount), Customer.Name
FROM 
    Customer 
INNER JOIN 
    Bill ON Customer.ID = Bill.Customer_ID
WHERE 
    Bill.date BETWEEN #20150101# AND #20151231#
GROUP BY 
    Customer.Name

The difficult part is that i need to display the results of that query for multiple years in a single table like this:

+-------------------------------------------+
|             sales to customer             |
+-------------------------------------------+
| Customer_ID | Customer_Name | 2015 | 2014 |
+-------------+---------------+------+------+
| 1           | jack          | 10$  | 20$  |
+-------------+---------------+------+------+
| 2           | john          | 55$  | 20$  |
+-------------+---------------+------+------+

I'm using SQL Server 2005.

I'm very grateful for every answer.

sincerly Andahari

Andahari
  • 35
  • 1
  • 5

2 Answers2

1

Use a case to only sum values corresponding to your time period. Example:

SELECT sum(case when Bill.date BETWEEN #20150101# AND #20151231# then Bill.amount else 0 end) as 2015, 
Customer.Name
    FROM Customer INNER JOIN Bill ON Customer.ID = Bill.Customer_ID
    GROUP BY Customer.Name
AdrianBR
  • 2,762
  • 1
  • 15
  • 29
  • OP wants to display data for several years Your answer does not correspond to OP's question. – Maciej Los Aug 25 '15 at 09:20
  • @MaciejLos change the filter? It responds exactly to the OP's question, and gives an example. It also uses sql standard and no subqueries, making it both efficient and compatible with all sql flavors. – AdrianBR Aug 25 '15 at 09:27
1

As stated you need to use a PIVOT in order to achieve the results you are looking for, like this:

Select Customer_ID, Customer_Name, [2015], [2014]
from
(select Customer_ID, Name Customer_Name, YEAR(_date) Yr, amount
from Bill b
inner join Customer c on c.ID = b.Customer_ID
) as src
PIVOT
(SUM(amount) for Yr in ([2015],[2014])) as pvt
Christian Barron
  • 2,695
  • 1
  • 14
  • 22