2016-01-03 45 views
1

我嘗試根據條件求和值,但是當我嘗試查詢時出現錯誤。在選擇列表中無效,因爲它不包含在聚合或Groupby子句中

如果case條件滿足,我需要求和它否則我不希望這種情況條件(求和值)被執行(爲了激活case條件我已經設置了一個變量(@rcntInputunit爲2)當的情況下是無效的(@rcntInputunit 1)查詢應該甚至不工作。

我想查詢的代碼如下所示。

BEGIN 
    DECLARE @rcntInputunit AS INT 
    SET @rcntInputunit =2 
    CREATE TABLE #MathLogicTable 
(
    IDNUM INTEGER IDENTITY(1,1), 
    FORMULA Varchar(160), 
    INPUTName varchar(160), 
    AttributeValue Decimal(15,3), 
    yearmonth varchar(160), 
    Unit int 
     ) 
    INSERT INTO #MathLogicTable 
VALUES(
'imports(398)+imports(399)', 
'imports(398)', 
46, 
'2003:2', 
15 
) 

INSERT INTO #MathLogicTable 
VALUES(
'imports(398)+imports(399)', 
'imports(399)', 
3, 
'2003:1', 
183 
) 

INSERT INTO #MathLogicTable 
VALUES(
'imports(398)+imports(399)', 
'imports(399)', 
85, 
'2003:2', 
15 
) 

INSERT INTO #MathLogicTable 
VALUES(
'imports(398)+imports(399)', 
'imports(399)', 
12, 
'2003:1', 
15 
) 

    INSERT INTO #MathLogicTable 
    VALUES(
'imports(398)+imports(399)', 
'imports(399)', 
41, 
'2003:2', 
183 
) 


     INSERT INTO #MathLogicTable 
     VALUES(
      'imports(398)+imports(399)', 
      'imports(398)', 
      12, 
      '2003:1', 
      183 
      ) 

     INSERT INTO #MathLogicTable 
     VALUES(
     'imports(398)+imports(399)', 
     'imports(398)', 
     10, 
     '2003:2', 
     183 
      ) 

     INSERT INTO #MathLogicTable 
     VALUES(
     'imports(398)+imports(399)', 
     'imports(398)', 
     5, 
     '2003:1', 
     15 
     ) 

Select FORMULA,INPUTName, Case when @rcntInputunit >1 THEN sum(AttributeValue) ELSE AttributeValue END AS Value ,yearmonth 
from #MathLogicTable 
GROUP BY 
FORMULA, 
INPUTName, 
yearmonth 
END 
--drop table #MathLogicTable 

有人可以告訴我什麼是錯誤的IM做查詢?

回答

2

當您使用GROUP BY您的選擇列表中的所有內容必須位於GROUP BY列表中(即FORMULA,INPUTNameyearmonth)或被包括在聚合函數中。

在你的情況下,有一列,即AttributeValue既不分組也不聚集。

Select 
    FORMULA 
, INPUTName 
, Case when @rcntInputunit >1 THEN 
     sum(AttributeValue) 
    ELSE 
     AttributeValue -- <<== Here 
    END AS Value 
, yearmonth 
from #MathLogicTable 
GROUP BY 
    FORMULA 
, INPUTName 
, yearmonth 
END 

爲了解決這個問題,你需要決定你想其中一組中的許多項目提供作爲結果Value柱,然後移動內部SUM條件:

SUM(
    CASE when @rcntInputunit > 1 OR (you-want-this-row's AttributeValue) THEN 
     AttributeValue 
    END 
) AS Value 
相關問題