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

实现如下结果,sql如何实现
本帖最后由 iseedoitright 于 2012-10-25 23:23:00 编辑
表tbUser如下:

UserID UserName
----------- --------------------
1 Peter
2 Tom
3 Jhon
4 Bob
5 Jack

表tbRecord如下:

RecordID UserID RecordDate
----------- ----------- -----------------------
1 1 2012-10-01 12:00:00.000
2 1 2012-01-20 14:20:53.000
3 1 2012-03-04 09:00:00.000
4 1 2012-01-05 13:00:03.000
5 1 2012-05-06 08:45:23.000
6 2 2012-01-23 14:22:32.000
7 2 2012-01-12 23:00:00.000
8 2 2012-02-04 10:11:14.000
9 2 2012-03-22 11:56:43.000
10 2 2012-02-01 04:23:00.000
11 3 2012-05-06 12:44:23.000
12 3 2012-07-08 05:54:23.000
13 3 2012-05-30 20:34:48.000
14 4 2012-09-19 23:59:00.000
15 5 2012-04-22 21:33:44.000
16 5 2012-04-18 08:38:48.000
17 5 2012-04-12 07:38:21.000
18 1 2012-10-01 22:33:44.000
19 1 2012-01-20 23:38:12.000

求2012年每个用户每个月有多少天的记录数,

比如 peter用户在表tbRecord中,2012年1月有2天的记录数(虽然1月1日有3条记录,但只能算是一天的记录),2月份0天的记录。。。

结果需要如下:其中省略了4到12月份

username 1 2 3
-------------------- ----------- ----------- -----------
Peter 2 0 1
Tom 2 2 1
Jhon 0 0 0
Bob 0 0 0
Jack 0 0 0

以上只是列出2012年,还有其他年份,数据不只这些,只是列出几行数据,先假设tbUser有30行数据,tbRecord有几百万数据,写出sql(oracle)语句实现。

------解决方案--------------------
select UserName,
(select count(distinct(to_char(RecordDate,'yyyymmdd'))) from tbRecord b where a.userid=b.userid and to_char(RecordDate,'yyyymm')='201201') 1月份记录数,
(select count(distinct(to_char(RecordDate,'yyyymmdd'))) from tbRecord b where a.userid=b.userid and to_char(RecordDate,'yyyymm')='201202') 2月份记录,
...........
 from tbUser a
------解决方案--------------------
--RecordDate是date型?
select UserName,
 sum(decode(month, 1, 1, 0)) "1",
 sum(decode(month, 2, 1, 0)) "2",
 sum(decode(month, 3, 1, 0)) "3",
 sum(decode(month, 4, 1, 0)) "4",
 sum(decode(month, 5, 1, 0)) "5",
 sum(decode(month, 6, 1, 0)) "6",
 sum(decode(month, 7, 1, 0)) "7",
 sum(decode(month, 8, 1, 0)) "8",
 sum(decode(month, 9, 1, 0)) "9",
 sum(decode(month, 10, 1, 0)) "10",
 sum(decode(month, 11, 1, 0)) "11",
 sum(decode(month, 12, 1, 0)) "12" from (
select UserName,  extract(month from max(RecordDate) ) month from tbRecord left join tbUser on tbUser.UserID=tbRecord.UserID
where RecordDate between to_date('2012-01-01', 'yyyy-mm-dd') and to_date('2013-01-01', 'yy