列在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中

时间:2016-02-26 14:23:07

标签: sql-server

    SELECT t0.testid,
 t0.pt500,
 t0.pt600,
 t1.id,
 t1.pt100,
 t1.pt200,
 t1.pt300  ,
     ( SELECT AVG(testid) FROM ab_Test ) AS testid_AVERAGE,
 ( SELECT MIN(testid) FROM ab_Test ) AS testid_MINIMUM,
 ( SELECT MAX(testid) FROM ab_Test ) AS testid_MAXIMUM,
 ( SELECT STDEV(testid) FROM ab_Test ) AS testid_STANDARDDEVIATION,
 ( SELECT SUM(testid) FROM ab_Test ) AS testid_TOTAL,
      ( SELECT COUNT(testid) FROM ab_Test ) AS testid_COUNT FROM sampletest t0
    Join ab_Test t1 ON (t0.testid=t1.id)

这给了我错误。我的表格结构如下:

id pt100 pt200 pt300 inverter1 voltage1 
1   1   0   2   1   5   20  2   20  0   2016-02-23 16:33:10.080
2   0   0   2   1   5   20  2   20  0   2016-02-23 16:35:40.320
3   0   0   2   1   5   20  2   20  0   2016-02-23 16:39:26.860
4   0   0   2   1   5   20  2   20  0   2016-02-23 16:39:40.133
5   0   0   2   1   5   20  2   20  0   2016-02-23 16:42:20.407
testid pt500 pt600 cdt
1   3   5   2016-02-23 16:33:10.080

当我宣布加入时,我收到错误,如我的问题所示。为什么它会给我错误,如果你能简单解释一下,那将是非常有帮助的。当我按下面添加组时:

group by t0.testid, t0.pt500, t0.pt600, t1.id, t1.pt100, t1.pt200, t1.pt300

我收到了以下错误。

  

子查询返回的值超过1。这是不允许的   子查询跟随=,!=,<,< =,>,> =或当子查询用作   表达。

我知道这是一个重复的问题,但我无法理解其他人的解释。

2 个答案:

答案 0 :(得分:0)

很难弄清楚你在做什么,但这样做并不正确。我猜你真正想要的是什么,但我认为这应该非常接近。

with TestValues as
(    
    SELECT testid 
        , AVG(testid) AS testid_AVERAGE
        , MIN(testid) FROM ab_Test AS testid_MINIMUM
        , MAX(testid) FROM ab_Test AS testid_MAXIMUM
        , STDEV(testid) FROM ab_Test AS testid_STANDARDDEVIATION
        , SUM(testid) AS testid_TOTAL
        , COUNT(testid) AS testid_COUNT
    FROM ab_Test
    group by testid
)

SELECT t0.testid
    , t0.pt500
    , t0.pt600
    , t1.id
    , t1.pt100
    , t1.pt200
    , t1.pt300  
FROM sampletest t0
Join ab_Test t1 ON t0.testid = t1.id
join TestValues tv on tv.testid = t0.testid

答案 1 :(得分:0)

希望这有帮助..此代码未经过测试..

SELECT t0.testid,
     t0.pt500,
     t0.pt600,
     t1.id,
     t1.pt100,
     t1.pt200,
     t1.pt300  ,
    AVG(testid)  AS testid_AVERAGE,
    MIN(testid)  AS testid_MINIMUM,
    MAX(testid)  AS testid_MAXIMUM,
    STDEV(testid) AS testid_STANDARDDEVIATION,
    SUM(testid)  AS testid_TOTAL,
    COUNT(testid AS testid_COUNT 
        FROM sampletest t0
        Join ab_Test t1 
        ON t0.testid=t1.id

        group by t0.testid, t0.pt500, t0.pt600, t1.id, t1.pt100, t1.pt200, t1.pt300