合计字段怎样给定权值排序?

microlife 2008-03-26 09:52:36
T_tag(title,tag)

select title, count(tag) from T_tag group by title where tag="tag1" or tag="tag2" order by count(tag) desc

这样得到的结果是所有标有tag1或tag2的title按照标签数的降序排列。

现在希望对tag1和tag2设权值,以影响排序结果,例如
tag1.weight=100
tag2.weight=50

希望order by (100*count(tag1)+50*count(tag2)),也就是按照一个自定义的权值来实现排序,这个权值并不在表中。

如果两者权值相同是可以用sum函数实现的:
select title, sum(count1) from (select title, count(*) as count1 from t_tag where tag="tag1" or tag="tag2" group by title and tag) group by title order by sum(count1)

但是现在希望能够在外面设定权值,怎么做呢?似乎要做一个视图,把下面两条语句里的记录合到一个表里面,然后再SUM

select title, 100*count(*) as count1 from t_tag where tag="tag1" group by title
select title, 50*count(*) as count1 from t_tag where tag="tag2" group by title
这样的视图怎么用SQL写呢?ACCESS中能做吗?
...全文
103 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
microlife 2008-03-26
  • 打赏
  • 举报
回复
问题解决了,access里面可以用IIF 或 SWITCH实现类似的功能,看来SQL还是满灵活的,学习了。
microlife 2008-03-26
  • 打赏
  • 举报
回复
多谢!括号里面部分是SQL的扩展吧?是不是要在存储过程里面才能用?还有,我现在用的是ACCESS数据库怎么办?
wzy_love_sly 2008-03-26
  • 打赏
  • 举报
回复
create  table tb(name varchar(10))
insert into tb select 'a'
insert into tb select 'a'
insert into tb select 'b'
insert into tb select 'b'

select name,sum(case when name='a' then 100 when name='b' then 50 end) as [sum]
from tb
group by name
order by sum(case when name='a' then 100 when name='b' then 50 end)


b 100
a 200
microlife 2008-03-26
  • 打赏
  • 举报
回复
不好意思,第二行group by子句应该放到where子句后面。。。
microlife 2008-03-26
  • 打赏
  • 举报
回复
这句翻译成大白话是说,在表中找某个title被标签为tag1的记录个数乘以权值100,tag2的乘50,最后求和,再按照这个求和的值来排序。
microlife 2008-03-26
  • 打赏
  • 举报
回复
后面一部分是我自己的思路,看不懂没关系。
前面7行看懂了吧?就是说能自己设定标签的重要性来排序,这可是今后web2.0的发展方向啊。。
wzy_love_sly 2008-03-26
  • 打赏
  • 举报
回复
order by (100*count(tag1)+50*count(tag2))

这句,
还有权值我基本没看懂

不如给点数据,给个结果好理解
microlife 2008-03-26
  • 打赏
  • 举报
回复
哪一句没懂?
wzy_love_sly 2008-03-26
  • 打赏
  • 举报
回复
没看懂,楼主

34,590

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧