sql server:通过赋值来创建排序列表

时间:2014-06-10 13:54:18

标签: sql-server

我有一个包含10个条目的表Surveyhttp://i.imgur.com/9pvqWEW.png。 10个用户必须提交1-5项的排名列表。 1是最重要的。如何编写可以为每列分配权重的查询,计算项目在该列中出现的次数,并使用“得分”返回排名列表1-5中的5项。这甚至可以用SQL Server吗?

因此,我认为每个项目在Growth1列中出现时都会+5。列Growth2等+4到

这是创建排名列表的最佳方式吗?

期望的输出:可能

1   Market Share                   45
2   Disease Profile Development    30
3   Physician Recruitment          28
4   Referrals                      21
5   Splitters                      18

2 个答案:

答案 0 :(得分:0)

SELECT ROW_NUMBER() OVER (ORDER BY 
ISNULL(b.count_1,0) + 
ISNULL(c.count_2,0) + 
ISNULL(d.count_3,0) + 
ISNULL(e.count_4,0) + 
ISNULL(f.count_5,0) DESC) AS rank
,a.categories
,ISNULL(b.count_1,0) + ISNULL(c.count_2,0) + ISNULL(d.count_3,0) + ISNULL(e.count_4,0) + ISNULL(f.count_5,0) AS total_score FROM

(SELECT DISTINCT Growth1 AS categories FROM [TESTDB].[dbo].[testtable]
UNION SELECT DISTINCT Growth2 AS categories FROM [TESTDB].[dbo].[testtable]
UNION SELECT DISTINCT  Growth3 AS categories FROM [TESTDB].[dbo].[testtable]
UNION SELECT DISTINCT  Growth4 AS categories FROM [TESTDB].[dbo].[testtable]
UNION SELECT DISTINCT  Growth5 AS categories FROM [TESTDB].[dbo].[testtable]) AS a

LEFT JOIN
(SELECT Growth1, COUNT(Growth1) * 5 AS count_1
FROM  [TESTDB].[dbo].[testtable]
GROUP BY Growth1) AS b
ON a.categories = b.Growth1

LEFT JOIN
(SELECT Growth2, COUNT(Growth2) * 4  AS count_2
FROM  [TESTDB].[dbo].[testtable]
GROUP BY Growth2) AS c
ON a.categories = c.Growth2

LEFT JOIN
(SELECT Growth3, COUNT(Growth3) * 3  AS count_3
FROM  [TESTDB].[dbo].[testtable]
GROUP BY Growth3) AS d
ON a.categories = d.Growth3

LEFT JOIN
(SELECT Growth4, COUNT(Growth4) * 2  AS count_4
FROM  [TESTDB].[dbo].[testtable]
GROUP BY Growth4) AS e
ON a.categories = e.Growth4

LEFT JOIN
(SELECT Growth5, COUNT(Growth5) * 1  AS count_5
FROM  [TESTDB].[dbo].[testtable]
GROUP BY Growth5) AS f
ON a.categories = f.Growth5

答案 1 :(得分:0)

您可以通过在几个常见的表表达式中将其拆分来简化查询;

WITH cte AS (
  SELECT 5 score, growth1 area FROM mytable
  UNION ALL
  SELECT 4 score, growth2 area FROM mytable
  UNION ALL
  SELECT 3 score, growth3 area FROM mytable
  UNION ALL
  SELECT 2 score, growth4 area FROM mytable
  UNION ALL
  SELECT 1 score, growth5 area FROM mytable
), cte2 AS (
  SELECT area, SUM(score) score FROM cte GROUP BY area
  HAVING area IS NOT NULL
), cte3 AS (
  SELECT area, score, 
    RANK() OVER (ORDER BY score DESC) rank
  FROM cte2
)
SELECT rank, area, score
FROM cte3
ORDER BY rank;

cte1基本上只是从每一列中提取数据以及相关的分数 cte2按区域总和得分。
cte3对每个区域的总分进行排名 外部查询只按排名对结果进行排序。

An SQLfiddle to test with