d*******n 发帖数: 109 | 1 一时半会想不清楚了,比较急,请帮助
数据模型简单,一共三个Table
第一个
id description
1 0-2y
2 2-5y
3 5-10y
4 more than 10y
第二个
userId id
1 1
2 NULL
3 4
4 3
5 NULL
6 1
7 NULL
第三个
userId Program
1 A
2 B
3 B
4 C
5 A
6 C
7 A
在SSRS里面, 我想
row 显示的是
0-2y
2-5y
5-10y
more than 10y
column显示的是不同的Program A, B and C
Matrix的数据显示的是count
比如,在上面的例子里应该是
A B C
0-2 1 0 1
2-5 0 0 0
5-10 0 0 1
more than 10 0 1 0
请问该如何准备query, 谢谢。 | u*********e 发帖数: 9616 | 2 把所有user都选出来放一个dataset里,然后用rdlc里面table row和column groupby
function
select * from table2 inner join table 1 on 2.id=1.id
inner join table3 on 3.userid=2.userid | d*******n 发帖数: 109 | 3 create table table1 (id int , description varchar(20))
insert into table1 values (1, '0-2')
insert into table1 values (2, '2-5')
insert into table1 values (3, '5-10')
insert into table1 values (4, 'more than 10')
create table table2 (userid int, id int)
insert into table2 (userid, id) values (1,1)
insert into table2 (userid, id) values (2,NULL)
insert into table2 (userid, id) values (3,4)
insert into table2 (userid, id) values (4,3)
insert into table2 (userid, id) values (5,NULL)
insert into table2 (userid, id) values (6,1)
insert into table2 (userid, id) values (7,NULL)
create table table3 (userid int, program char(1))
insert into table3 values (1, 'A')
insert into table3 values (2, 'B')
insert into table3 values (3, 'B')
insert into table3 values (4, 'C')
insert into table3 values (5, 'A')
insert into table3 values (6, 'C')
insert into table3 values (7, 'A')
select * from table1
select * from table2
select * from table3
好像不对啊 | d*******n 发帖数: 109 | 4 我这里最后需要显示所有的Description, 如果一个Program没有数值,就显示0。 | d*******n 发帖数: 109 | 5 后来自己解决了这个问题,用的是笨办法,一步一步做出来了,但是肯定有好方法,用
subquery之类的,只是自己笨,想不出来而已。 | l******b 发帖数: 39 | 6
是要这样吗?
With C As(
select description, t2.userid, program
from table1 as t1
left join table2 as t2
on t1.id = t2.id
left join table3 as t3
on t2.userid = t3.userid
)
select description, A, B, C
from C pivot(count(userid) for program in (A, B, C)) as P ;
----------------------------------------------------------
description A B C
---------------------------
0-2 1 0 1
2-5 0 0 0
5-10 0 0 1
more than 10 0 1 0
【在 d*******n 的大作中提到】 : 我这里最后需要显示所有的Description, 如果一个Program没有数值,就显示0。
| d*******n 发帖数: 109 | 7 是的,谢谢。
顺便问一句,像这样的问题,是不是总是可以用subquery或者是table join加以解决?
如果是table join的话,为了确保不遗漏任何数据,必须在所以的table之间都用left
join ? 比如有10个table, 那必须用九个left join ? 谢谢。
【在 l******b 的大作中提到】 : : 是要这样吗? : With C As( : select description, t2.userid, program : from table1 as t1 : left join table2 as t2 : on t1.id = t2.id : left join table3 as t3 : on t2.userid = t3.userid : )
| l******b 发帖数: 39 | 8
left
恩, 记得好像是这样的.
inner join 或者 where子句会过虑掉outer query的outer rows,
所以要么全部用left join,要么用()改变连接的顺序
【在 d*******n 的大作中提到】 : 是的,谢谢。 : 顺便问一句,像这样的问题,是不是总是可以用subquery或者是table join加以解决? : 如果是table join的话,为了确保不遗漏任何数据,必须在所以的table之间都用left : join ? 比如有10个table, 那必须用九个left join ? 谢谢。
| d*******n 发帖数: 109 | |
|