我将首先尝试解释这个场景。 有一个Web应用程序,其表单包含许多字段。我想将其中两个字段相加,以便与另一个值进行比较。
数据库中的表包含一个名为dollar value
的列。所有这些字段都有ID
。因此,为了从特定用户的字段中检索值,我打电话询问特定用户的特定ID
。
但是,此表包含系统中所有用户的所有字段的所有值。含义,表中的每一行代表特定字段的特定用户的值。
问题是,如何将field 1
添加到field 2
并检查它是否等于所有用户的值。
示例表
+====+==========+==============+
| ID | Field ID | Dollar Value |
+====+==========+==============+
| 1 | 123 | 35.00 |
+----+----------+--------------+
| 2 | 123 | 24.56 |
+----+----------+--------------+
| 3 | 543 | 10.00 |
+----+----------+--------------+
| 4 | 543 | 21.00 |
+----+----------+--------------+
我需要添加id 1
+ id 3
并检查它是否等于某个值。
答案 0 :(得分:0)
您可以使用下面的简单查询来获取+
+ id 1
的总数:
id 3
但是,我不知道你想要如何比较总值和值,你想要执行什么比较(例如,等于,大于或小于等),以及比较时你想做什么是SELECT SUM([Dollar Value])
FROM [Table]
WHERE ID IN(1, 3)
或true
。
如果您想在SQL中进行比较,请假设您想要在总价超过100美元时进行促销。你可以这样做:
false
答案 1 :(得分:0)
根据您目前发布的内容(包括最近的评论),我认为GROUP BY和CASE应该适合您。
例如(注意LEFT JOIN
,如果你提到的“其他”表中没有相应的TargetValue,那么:
SELECT tt.[FieldID], SUM(tt.[DollarValue]) AS 'CalculatedSUM', tv.TargetValue
,CASE WHEN SUM(tt.[DollarValue]) = tv.[TargetValue]
THEN 'EqualValue'
ELSE 'NotEqualValue'
END AS 'ValueCheckTest'
FROM TestTable tt
LEFT JOIN TargetValue tv ON tt.FieldID = tv.FieldID
GROUP BY tt.[FieldID], tv.[TargetValue]
以下是我用来测试的代码,结果如下:
CREATE TABLE [dbo].[TestTable](
[ID] [INT] IDENTITY(1,1) NOT NULL,
[FieldID] [INT],
[DollarValue] [DECIMAL](19,2)
CONSTRAINT [PK_TestTable_ID] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)
) ON [PRIMARY]
GO
--Create table with constraint FieldID + TargetValue (ex. 123,59.56) only allowed once.
CREATE TABLE [dbo].[TargetValue](
[ID] [INT] IDENTITY(1,1) NOT NULL,
[FieldID] [INT],
[TargetValue] [DECIMAL](19,2),
CONSTRAINT [PK_TargetValue_ID] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)
, CONSTRAINT [UQ_TargetValue] UNIQUE NONCLUSTERED
(
[FieldID], [TargetValue]
)) ON [PRIMARY]
GO
INSERT INTO [dbo].[TestTable]
SELECT '123','35.00' UNION ALL
SELECT '123','24.56' UNION ALL
SELECT '543','10.00' UNION ALL
SELECT '543','21.00' UNION ALL
SELECT '999','99.99'
GO
--maybe you have more than one TargetValue for a specific item
INSERT INTO [dbo].[TargetValue]
SELECT '123','59.56' UNION ALL
SELECT '543','150.00' UNION ALL
SELECT '543','59.56'
GO
SELECT tt.[FieldID], SUM(tt.[DollarValue]) AS 'CalculatedSUM', tv.TargetValue
,CASE WHEN SUM(tt.[DollarValue]) = tv.[TargetValue]
THEN 'EqualValue'
ELSE 'NotEqualValue'
END AS 'ValueCheckTest'
FROM TestTable tt
LEFT JOIN TargetValue tv ON tt.FieldID = tv.FieldID
GROUP BY tt.[FieldID], tv.[TargetValue]
--DROP TABLE dbo.[TestTable]
--DROP TABLE dbo.[TargetValue]