从同一表添加列到查询,更新重复列中的值?

时间:2016-05-10 02:37:34

标签: sql sql-server

我正试图弄清楚这个。在这种情况下,该数据库中特定城市的天然气价格正在上涨,因此他们需要将价格提高20%。我应该创建一个查询,只显示该城市的新价格。这是它应该是什么样子:

enter image description here

这是我的代码:

Select ProductID, tblProduct.ProductType, Price, SUM((Price *.20)+Price) AS 'Increased Price'
From tblProduct join tblCompany
    On tblProduct.CompanyID = tblCompany.CompanyID
Where tblCompany.CompanyID IN
    (Select CompanyID
    From tblCompany
    Where City = 'Kalamazoo')
Order By ProductID

但是,当我去执行代码时,我收到以下错误:

  

Msg 8120,Level 16,State 1,Line 1   列'tblProduct.ProductID'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。

我无法弄清楚我做错了什么。谁能开导我?

3 个答案:

答案 0 :(得分:1)

如果您只计算20%的价格上涨,那么您真的不需要SUM函数......请改为

Sub Copy_Folder()
'This example copy all files and subfolders from FromPath to ToPath.
'Note: If ToPath already exist it will overwrite existing files in this folder
'if ToPath not exist it will be made for you.
    Dim FSO As Object
    Dim FromPath As String
    Dim ToPath As String

    FromPath = "C:\Process_Contract_Notes"  '<< Change
    ToPath = "C:\Process"    '<< Change


    If Right(FromPath, 1) = "\" Then
        FromPath = Left(FromPath, Len(FromPath) - 1)
    End If

    If Right(ToPath, 1) = "\" Then
        ToPath = Left(ToPath, Len(ToPath) - 1)
    End If

    Set FSO = CreateObject("scripting.filesystemobject")

    If FSO.FolderExists(FromPath) = False Then
        MsgBox FromPath & " doesn't exist"
        Exit Sub
    End If

    FSO.CopyFolder Source:=FromPath, Destination:=ToPath
    MsgBox "You can find the files and subfolders from " & FromPath & " in " & ToPath

End Sub

答案 1 :(得分:1)

Select tblProduct.ProductID, tblProduct.ProductType, tblProduct.Price, SUM((tblProduct.Price *.20)+tblProduct.Price) AS 'Increased Price'
From tblProduct join tblCompany
    On tblProduct.CompanyID = tblCompany.CompanyID
Where tblCompany.CompanyID IN
    (Select c.CompanyID
    From tblCompany c
    Where c.City = 'Kalamazoo')
Order By ProductID

答案 2 :(得分:0)

name1 | name2 | id | +----------------+--------------+-----------+ | A | J | 2 | | B | K | 2 | | C | L | 2 | | D | M | 2 | | A | N | 2 | 建议使用聚合查询。您没有SUM(),因此初始列(GROUP BY等)无效。

将表别名用于查询是个好主意。这些使查询更容易编写和阅读。所以:

ProductId

此外,Select p.ProductID, p.ProductType, p.Price, ((p.Price * 1.20) AS IncreasedPrice From tblProduct p join tblCompany c On p.CompanyID = c.CompanyID Where c.City = 'Kalamazoo' Order By p.ProductID; 子句是不必要的。您可以使用IN检查城市。

相关问题