Home Database Mysql Tutorial 怎么在SQLServer计算列和平均值

怎么在SQLServer计算列和平均值

Jun 07, 2016 pm 04:21 PM
sqlserver average value how calculate

严格来说,Having并不需要一个子表,但没有子表的Having并没有实际意义。如果你只需要一个表,那么你可以用Where子句达到一切目的。为进行实践,Having预先假定至少两个表和一个基于第二个表的合计函数。 下面是一个简单的例子:你想要订单总数超过25000美元

  严格来说,Having并不需要一个子表,但没有子表的Having并没有实际意义。如果你只需要一个表,那么你可以用Where子句达到一切目的。为进行实践,Having预先假定至少两个表和一个基于第二个表的合计函数。

  下面是一个简单的例子:你想要订单总数超过25000美元的客户清单。你需要适当连接的三个表:Customer、SalesOrderHeader和SalesOrderDetail。然后,你求Detail的和,并将总数与25000美元进行比较。查看列表A。

  查看列表A中的代码时,有一件事情并不明显,即LineTotal列被计算。你可以像求实际的列的和一样求出已计算列的和。但是,你不能在同一个操作中执行两个不同层次的合计函数。

  SELECT

  Sales.Customer.CustomerID,

  Sales.SalesOrderHeader.SalesOrderID,

  SUM(Sales.SalesOrderDetail.LineTotal)

  AS SubTotalFROM

  Sales.Customer

  INNER JOIN Sales.SalesOrderHeader

  ON Sales.SalesOrderHeader.Customer

  ID = Sales.Customer.CustomerID

  INNER JOIN Sales.SalesOrderDetail

  ON Sales.SalesOrderDetail.SalesOrder

  ID = Sales.SalesOrderHeader.SalesOrderIDGROUP BY

  Sales.Customer.CustomerID,

  Sales.SalesOrderHeader.SalesOrder

  IDHAVING SUM(LineTotal) > 25000.00ORDER BY

  Sales.Customer.CustomerID,

  SalesOrderID ;列表A:

  假设你希望知道所有客户的平均销售额。你可以使用列表B中的代码,它返回如下错误信息:

  SELECT

  Sales.SalesOrderHeader.SalesOrderID,

  AVG(SUM(Sales.SalesOrderDetail.LineTotal))

  AS AverageFROM

  Sales.SalesOrderHeader

  INNER JOIN Sales.SalesOrderDetail

  ON Sales.SalesOrderDetail.SalesOrder

  ID = Sales.SalesOrderHeader.SalesOrder

  IDGROUP BY

  Sales.SalesOrderHeader.SalesOrderID列表B:

  Msg 130, Level 15, State 1, Line 1

  Cannot perform an aggregate function on an expression

  containing an aggregate or a subquery.错误信息:

  你可以将平均值的计算过程进行分解来解决这个问题。你可以将第一部分(SUM)编写成一个表值UDF,如列表C所示。你可以根据列表D中的函数计算平均值。列表E说明你如何能够进行组合。

  USE [AdventureWorks]

  GO

  /****** Object: UserDefinedFunction

  [dbo].[SalesTotals_fnt]

  Script Date: 12/09/2006 11:32:54 ******/

  SET ANSI_NULLS ON

  GO

  SET QUOTED_IDENTIFIER ON

  GO

  CREATE FUNCTION [dbo].[SalesTotals_fnt]()

  RETURNS TABLE

  AS RETURN

  (SELECT SalesOrderID,

  SUM(LineTotal)AS TotalSale

  FROM Sales.SalesOrderDetail

  GROUP BY Sales.SalesOrderDetail.SalesOrderID)列表C:

  CREATE FUNCTION [dbo].[AverageSale_fns] (

  -- Add the parameters for the function here

  -- )RETURNS money

  ASBEGIN

  -- Declare the return variable here

  DECLARE @Result money

  -- Add the T-SQL statements to compute the return value here

  SET @Result =(SELECTAvg(TotalSale)AS AverageSale

  FROM dbo.SalesTotals_fnt())

  -- Return the result of the function

  RETURN @Result

  END列表D:

  DECLARE @Avg moneySELECT @Avg = dbo.AverageSale_fns()

  SELECT *, @Avg as Average,

  TotalSale / @Avg as Ratio, CASE

  WHEN TotalSale / @Avg > 1 THEN 'Above Average'

  WHEN TotalSale / @Avg

  ELSE 'Average' END

  FROM dbo.SalesTotals_fnt()列表E:

  现在你知道了如何根据一个子表使用Having子句来测试合计值。当你需要在一个查询中使用两个不同的合计函数时,,最好是把它们分解成单独的函数,然后再进行组合(如前一个例子所说明的)。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to import mdf file into sqlserver How to import mdf file into sqlserver Apr 08, 2024 am 11:41 AM

The import steps are as follows: Copy the MDF file to SQL Server's data directory (usually C:\Program Files\Microsoft SQL Server\MSSQL\DATA). In SQL Server Management Studio (SSMS), open the database and select Attach. Click the Add button and select the MDF file. Confirm the database name and click the OK button.

How to solve the problem that the object named already exists in the sqlserver database How to solve the problem that the object named already exists in the sqlserver database Apr 05, 2024 pm 09:42 PM

For objects with the same name that already exist in the SQL Server database, the following steps need to be taken: Confirm the object type (table, view, stored procedure). IF NOT EXISTS can be used to skip creation if the object is empty. If the object has data, use a different name or modify the structure. Use DROP to delete existing objects (use caution, backup recommended). Check for schema changes to make sure there are no references to deleted or renamed objects.

CUDA's universal matrix multiplication: from entry to proficiency! CUDA's universal matrix multiplication: from entry to proficiency! Mar 25, 2024 pm 12:30 PM

General Matrix Multiplication (GEMM) is a vital part of many applications and algorithms, and is also one of the important indicators for evaluating computer hardware performance. In-depth research and optimization of the implementation of GEMM can help us better understand high-performance computing and the relationship between software and hardware systems. In computer science, effective optimization of GEMM can increase computing speed and save resources, which is crucial to improving the overall performance of a computer system. An in-depth understanding of the working principle and optimization method of GEMM will help us better utilize the potential of modern computing hardware and provide more efficient solutions for various complex computing tasks. By optimizing the performance of GEMM

What to do if the sqlserver service cannot be started What to do if the sqlserver service cannot be started Apr 05, 2024 pm 10:00 PM

When the SQL Server service fails to start, here are some steps to resolve: Check the error log to determine the root cause. Make sure the service account has permission to start the service. Check whether dependency services are running. Disable antivirus software. Repair SQL Server installation. If the repair does not work, reinstall SQL Server.

How to check sqlserver port number How to check sqlserver port number Apr 05, 2024 pm 09:57 PM

To view the SQL Server port number: Open SSMS and connect to the server. Find the server name in Object Explorer, right-click it and select Properties. In the Connection tab, view the TCP Port field.

How to recover accidentally deleted database in sqlserver How to recover accidentally deleted database in sqlserver Apr 05, 2024 pm 10:39 PM

If you accidentally delete a SQL Server database, you can take the following steps to recover: stop database activity; back up log files; check database logs; recovery options: restore from backup; restore from transaction log; use DBCC CHECKDB; use third-party tools. Please back up your database regularly and enable transaction logging to prevent data loss.

Where is the sqlserver database? Where is the sqlserver database? Apr 05, 2024 pm 08:21 PM

SQL Server database files are usually stored in the following default location: Windows: C:\Program Files\Microsoft SQL Server\MSSQL\DATALinux: /var/opt/mssql/data The database file location can be customized by modifying the database file path setting.

How to delete sqlserver if the installation fails? How to delete sqlserver if the installation fails? Apr 05, 2024 pm 11:27 PM

If the SQL Server installation fails, you can clean it up by following these steps: Uninstall SQL Server Delete registry keys Delete files and folders Restart the computer

See all articles