求一sql语句。。。
一个问答的数据,有三个表
user
question
checked是否通过审核
overid 是 表answer的id,表明该回答是问题的最佳回答
pubid是user的id
answer
现在我只会在一个表里查询
比如7天内发表问题总数排名的前三甲
select nick(昵称), jifen(7天内的积分), count_question(7天内的问题数), count_answer(7天内的回答数), count_best(7天内的最佳答案)
SELECT pubid ,SUM([count_question(7天内的问题数)] ) AS [count_question(7天内的问题数)]
,SUM([count_answer(7天内的回答数)]) AS [count_answer(7天内的回答数)]
,SUM([count_best(7天内的最佳答案)]) AS [count_best(7天内的最佳答案)]
,SUM([jifen(7天内的积分)]) AS [jifen(7天内的积分)]
FROM (
SELECT pubid ,1 AS [count_question(7天内的问题数)],0 AS [count_answer(7天内的回答数)],0 AS [count_best(7天内的最佳答案)]
, 10 AS [jifen(7天内的积分)]
from question
where checked = 1
and datediff(d, pubtime, getdate()) <= 7
UNION ALL
SELECT A.pubid ,0 AS [count_question(7天内的问题数)],0 AS [count_answer(7天内的回答数)],1 AS [count_best(7天内的最佳答案)]
,10 [jifen(7天内的积分)]
from answer A INNER JOIN question Q
ON A.ID = Q.overid
where A.checked = 1
and datediff(d, A.pubtime, getdate()) <= 7
UNION ALL
SELECT pubid ,0 AS [count_question(7天内的问题数)],1 AS [count_answer(7天内的回答数)],0 AS [count_best(7天内的最佳答案)]
, 10 AS [jifen(7天内的积分)]
from answer
where checked = 1
and datediff(d, pubtime, getdate()) <= 7
) AS T
GROUP BY pubid
USE test
GO
---->生成表User
--
--if object_id('User') is not null
--drop table [User]
--Go
--Create table [User]([id] int,[nick] nvarchar(50),[jifen] int)
--Insert into [User]
--Select 1,'test','5'
--Union all Select 2,'test2','10'
---->生成表question
--
--if object_id('question') is not null
--drop table question
--Go
--Create table question([id] int,[checked] bit,[overid] int,[pubid] int,[title] nvarchar(50),[content] nvarchar(400),[pubtime] DATETIME)
--Insert into question
--Select 1,1,1,2,'t1','t2','20130109'
--Union all Select 2,0,NULL,1,'t1','t2','20130109'
--
---->生成表answer
--
--if object_id('answer') is not null
--drop table answer
--Go
--Create table answer([id] int,[checked] bit,[pubid] int,[content] nvarchar(400),[pubtime] DATETIME)
--Insert into answer
--Select 1,1,1,'test___','20130110'
--Union all Select 2,0,2,'test2','20130111'
/*
select?nick(昵称),?jifen(7天内的积分),?count_question(7天内的问题数),?count_answer(7天内的回答数),?count_best(7天内的最佳答案)
*/
select
a.id
,a.nick
,SUM(CASE WHEN b.checked=1 THEN 10 ELSE 0 END+CASE WHEN c.checked=1 THEN 10 ELSE 0 END+CASE WHEN c.bestid IS NOT NULL THEN 20 ELSE 0 END) AS jifen
,COUNT(b.id) AS count_question
,COUNT(c.id) AS count_answer
,SUM(CASE WHEN c.bestid IS NOT NULL THEN 1 ELSE 0 END) AS count_best
from
[User] AS a
,(SELECT * FROM question AS x
WHERE x.pubtime BETWEEN DATEADD(dd,-7,getdate()) AND getdate()
) AS b
,(SELECT x.*,y.id AS bestid FROM answer AS x
LEFT JOIN question AS y ON x.id=y.overid
WHERE x.pubtime BETWEEN DATEADD(dd,-7,getdate()) AND getdate()
) AS c
WHERE b.pubid=a.id
AND c.pubid=a.id
GROUP BY
a.id,a.nick
/*
id nick jifen count_question count_answer count_best
--- ------- ------ -------------- ------------ -----------
1 test 30 1 1 1
2 test2 10 1 1 0
*/
Go