日期:2014-05-17  浏览次数:20743 次

简单的二维查询
一张表存地点,和该地点处的商品ID
一张表存放时间间隔和商品ID
现在查询
地点/间隔 0-10 10-100 100-200
A 1 2 3
B 4 5 6
C 7 8 9
D 1 11 12
E 3 2 4
这样的数据,其中地点从表中检索,时间间隔就是0-10,10-100,100-200,要统计的数据是该地点处,在这个间隔中的商品的个数。
================================
A 1 2 3
B 4 5 6
C 7 8 9
D 1 11 12
E 3 2 4
===============================
比方说A地   在100-200   间隔的数据为3,这个个数就是商品ID的个数
不知道说明白没有,用一句Sql能写吗?其中商品ID唯一
一个地点处多个商品ID,并且商品ID不会同时出现在两个地点。时间间隔表同。
等待高手。分不够再开帖子给分。

------解决方案--------------------
看不太懂你的意思
------解决方案--------------------
能否造些相关数据?
------解决方案--------------------
给些测试数据吧
------解决方案--------------------
“商品ID不会同时出现在两个地点。时间间隔表同。”
按照这种说法:
也就是说一个商品ID对应一个地点、一个时间间隔。
所以,你应该将两表按商品ID连接做成一张表。
然后按地点和时间间隔进行分组
最后涉及到的就是行列转换了。
------解决方案--------------------
要写存储过程实现哦
------解决方案--------------------
说错了,改了如下:
--建立测试环境
Create Table shopAddress1(address varchar(10),shopId int)
--插入数据
insert into shopAddress1
select 'A123 ', '1 ' union
select 'A123 ', '4 ' union
select 'A123 ', '5 ' union
select 'B456 ', '7 ' union
select 'B456 ', '6 ' union
select 'B456 ', '3 ' union
select 'B456 ', '114 ' union
select 'B456 ', '214 ' union
select 'C789 ', '14 ' union
select 'C789 ', '104 ' union
select 'C789 ', '141 ' union
select * from shopAddress1

Create Table shopD1(timeDiff(时间间隔) varchar(10),shopId int,total int)
--插入数据
insert into shopD1
select '1-10 ', '1 ' , '1 ' union
select '1-10 ', '4 ' , '1 ' union
select '1-10 ', '5 ' , '1 ' union
select '10-100 ', '7 ', '1 ' union
select '10-100 ', '6 ', '1 ' union
select '10-100 ', '3 ' , '1 ' union
select '100-200 ', '114 ', '1 ' union
select '100-200 ', '214 ', '1 ' union
select '1-10 ', '14 ', '1 ' union
select '10-100 ', '104 ', '1 ' union
select '100-200 ', '141 ', '1 ' union
select * from shopD1


select address, sum(case when timeDiff= '1-10 ' then total else 0 end ) [1-10],
sum(case when timeDiff= '10-100 ' then total else 0 end )[10-100],
sum(case when timeDiff= '100-200 ' then total else 0 end )[100-200]


from shopD1 a ,shopAddress1 b where a.shopId=b.shopId
group by address
测试结果:
address 1-10 10-100 100-200
A123 3 0 0
B456 0 3 2
C789 1 1 1
楼主,试试,别忘了给分哦



------解决方案--------------------
帮你顶一顶