我在 SQL Server 中有一个表,并且有一列我想从其他三列(Vendor1、Vendor2 和 Vendor3)中计算最小值。我已经弄清楚如何对这些值求和,但不知道如何找到最小值 - 我不断收到一个错误,即聚合可能不会出现在计算列中。有没有一种简单的方法来解决这个问题?
问问题
1259 次
3 回答
2
您可以使用CASE
表达式
CREATE TABLE T
(
Vendor1 INT,
Vendor2 INT,
Vendor3 INT,
MinVendor AS CASE
WHEN Vendor1 < Vendor2
AND Vendor1 < Vendor3 THEN Vendor1
WHEN Vendor2 < Vendor3 THEN Vendor2
ELSE Vendor3
END
)
但有列Vendor1 - 3
可能表明您的表不是第一范式。
于 2013-01-28T20:56:05.377 回答
1
试试这个:
CREATE FUNCTION dbo.MinOf3(@a int, @b int, @c int)
RETURNS INT
AS
BEGIN
RETURN (SELECT MIN(a) FROM (
SELECT @a a UNION ALL
SELECT @b UNION ALL
SELECT @c
) T(a)
)
END
GO
CREATE TABLE T(a1 int, a2 int, a3 int, a4 as dbo.MinOf3(a1, a2, a3))
于 2013-01-28T21:08:33.780 回答
0
MIN is as it says an aggreagate. It finds the minimum value of a column across all rows for a single column. It sounds like what you are trying to do is find the minimum in each row for across three columns. SQL does not have a built in function to do that, but it can be done with a simple CASE expression as Martin SMith has already shown.
You may also want to consider using a View rather than a Computed Column, which would allow you to do it this way as well.
SELECT OtherColumn,
(SELECT MIN(Vendor) AS Expr1
FROM (SELECT Vendor1 AS Vendor
UNION ALL
SELECT Vendor2
UNION ALL
SELECT Vendor3)) AS VendorMimum
FROM Vendors
于 2013-01-28T21:12:12.143 回答