Click here to Skip to main content
15,903,388 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a problem to query data.
There are some data shown in following.

Date		Loc	Amount
----------------------------
2010-01-02	place1	100
2010-01-14	place1	110
2010-02-11	place2	80
2010-02-11	place3	200
2010-04-20	place1	330
2010-04-22	place2	120
2010-04-26	place3	220
2010-05-01	place1	150
2010-05-03	place2	180
2010-05-06	place2	50
2010-05-06	place3	100
2010-05-11	place2	200


Then, the result must be between 2010-02-01 and 2010-02-28 and shown in following.

Loc	Amount
------------
place1	0
place2	80
place3	200


Sorry for my un-perfect english.
Posted

Solution:

select Loc, sum(amount) from tablename where date between '2010-02-01' and '2010-02-28' group by Loc
 
Share this answer
 
Thanks everyone. I found the solution.

SQL
CREATE TABLE #t1
(D1 DATETIME
, LOC NVARCHAR(10)
, AMOUNT INT)
GO
INSERT INTO #t1 VALUES('2010-01-02','place1',100)
INSERT INTO #t1 VALUES('2010-01-02','place1',100)
INSERT INTO #t1 VALUES('2010-01-14','place1',110)
INSERT INTO #t1 VALUES('2010-02-11','place2',80)
INSERT INTO #t1 VALUES('2010-02-11','place3',200)
INSERT INTO #t1 VALUES('2010-04-20','place1',330)
INSERT INTO #t1 VALUES('2010-04-22','place2',120)
INSERT INTO #t1 VALUES('2010-04-26','place3',220)
INSERT INTO #t1 VALUES('2010-05-01','place1',150)
INSERT INTO #t1 VALUES('2010-05-03','place2',180)
INSERT INTO #t1 VALUES('2010-05-06','place2',50)
INSERT INTO #t1 VALUES('2010-05-06','place3',100)
INSERT INTO #t1 VALUES('2010-05-11','place2',200)
GO
SELECT DISTINCT a.loc,ISNULL(b.amount,0) AS amount FROM #t1 as a
LEFT OUTER JOIN
(SELECT loc,
sum(amount) as amount
FROM #t1 as b
WHERE d1 >= '2010-02-01' AND d1 <= '2010-02-28'
GROUP BY loc) AS b
ON a.loc = b.loc
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900