从已连接的表

时间:2017-03-31 06:39:45

标签: sql sql-server

我有以下sql查询

SELECT m.School, c.avgscore 
FROM postswithratings c 
join ZEntrycriteria on c.fk_postID= m.schoolcode 

提供以下结果

School| avgscore
xyz   |  5
xyz   |  5
xyz   |  5
abc   |  3
abc   |  3
kkk   |  1

我的问题是如何删除这些副本并仅获取跟踪。

 School| avgscore
    xyz   |  5 
    abc   |  3
    kkk   |  1

我试过

   SELECT m.School, c.avgscore 
   FROM postswithratings c 
   join ZEntrycriteria on c.fk_postID= m.schoolcode 
   group by m.School 

但它给了我以下错误

  

"专栏&posts ;withwithratings.avgscore'在选择列表中无效   因为它不包含在聚合函数或   GROUP BY子句。"

6 个答案:

答案 0 :(得分:4)

无需复杂化。请跟:

SELECT m.School, c.avgscore 
FROM postswithratings c 
join ZEntrycriteria on c.fk_postID= m.schoolcode 
group by m.School, c.avgscore 

SELECT DISTINCT m.School, c.avgscore 
FROM postswithratings c 
join ZEntrycriteria on c.fk_postID= m.schoolcode 

答案 1 :(得分:1)

您只需添加如下所示的不同关键字: -

filebeat2017/04/19 06:54:22.450440 beat.go:339: CRIT Exiting: error loading config file: stat filebeat.yml: no such file or directory
Exiting: error loading config file: stat filebeat.yml: no such file or directory

答案 2 :(得分:0)

这将删除重复行(仅重复)

<强>架构:

CREATE TABLE #TAB (School varchar(5) , avgscore int)
INSERT INTO #TAB
SELECT 'xyz', 5
UNION ALL
SELECT 'xyz', 5
UNION ALL
SELECT 'xyz', 5
UNION ALL
SELECT 'abc', 3
UNION ALL
SELECT 'abc', 3
UNION ALL
SELECT 'kkk', 1

现在使用CTE作为您的Tempprary View并删除数据。

;WITH CTE AS(
SELECT ROW_NUMBER() OVER (PARTITION BY School,avgscore  ORDER BY (SELECT 1)) DUP_C, 
School,  avgscore FROM #TAB
)

DELETE FROM CTE WHERE DUP_C>1

现在检查#TAB,数据将是

+--------+----------+
| School | avgscore |
+--------+----------+
| xyz    |        5 |
| abc    |        3 |
| kkk    |        1 |
+--------+----------+

答案 3 :(得分:0)

CREATE TABLE #Table2
    ([School] varchar(3), [avgscore] int)

INSERT INTO #Table2
    ([School], [avgscore])
VALUES
    ('xyz', 5),
    ('xyz', 5),
    ('xyz', 5),
    ('abc', 3),
    ('abc', 3),
    ('kkk', 1)
;
SELECT  SCHOOL,AVGSCORE FROM (SELECT *,ROW_NUMBER() OVER( PARTITION BY [AVGSCORE] ORDER BY (SELECT NULL)) AS RN FROM #TABLE2)A
WHERE RN=1
ORDER BY AVGSCORE
-------
;WITH CTE AS
(SELECT *,ROW_NUMBER() OVER( PARTITION BY [AVGSCORE] ORDER BY (SELECT NULL)) AS RN FROM #TABLE2)
SELECT SCHOOL,AVGSCORE  FROM CTE WHERE RN=1

输出

SCHOOL  AVGSCORE
kkk      1
abc      3
xyz      5

答案 4 :(得分:0)

使用DISTINCT关键字将使sql使用集而不是多集。所以值只出现一次

答案 5 :(得分:0)

如果您正在使用聚合函数,则只使用group by,例如。最大。总之,平均

在那种情况下,

SELECT Distinct(m.School), c.avgscore 
FROM postswithratings c 
join ZEntrycriteria on c.fk_postID= m.schoolcode