sql - 来自另一个表的列计算
问题描述
我有两张桌子。首先是 HumanResources.Employees,另一个是 ProjectDetails.TimeCards b 我希望自动计算 ProjectDetailsTimeCards 上的 TotalCost 列,即 TotalCost=Billable Hours b * BillingRate a。它们可以与employee_ID 一起加入。但是我无法将其转换为表格格式。下表如下
Create table HumanResources.Employees (
Employee_ID int primary key identity (99, 11),
First_Name char (20) not null,
Phone_Number varchar (30) not null
CONSTRAINT chk_Phone_Number CHECK (Phone_Number like '[0-9][0-9]-[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]-[0-9][0-9][0-9]-[0-9][0-9][0-9]'),
Title char (35),
Billing_Rate int constraint chk_Billing_Rate check (Billing_Rate > '0')
); -- would be uses to multiply billing hours
create table ProjectDetails.TimeCards(
Time_Card_ID int identity (55,15) primary key,
Employee_ID int foreign key references HumanResources.Employees(Employee_ID), -- references primary key on the human_resources table
Date_Issued date,
Days_Worked int constraint chk_Days_Worked check(Days_Worked > '0'),
Project_ID int foreign key references ProjectDetails.Projects(Project_ID), -- foreign key reference
Billable_hours int constraint chk_Billable_Hours check (Billable_Hours > '0'),-- would be used to multiply billing rate
Total_Cost money, -- should automatically take TotalCost=Billable Hours b * BillingRate a
Work_Code_ID int foreign key references ProjectDetails.WorkCodes(Work_Code_ID)
);-- references primary key on another table
CREATE VIEW HumanResources.vwEmployeeData AS SELECT e.EmployeeID、e.Date_Issued、e.Days_Worked、e.Project_ID、e.Billable_Hours、e.Work_Code_ID——从第一个表中查看 FROM HumanResources.Employees e JOIN ProjectDetails.TimeCards d ON e。 Employee_ID = d.Employee_ID -- 我创建的视图
解决方案
您可以通过定义类似这样的函数来实现这一点
CREATE FUNCTION GetValue(@billablehours INT, @empid INT)
RETURNS INT
AS
SELECT @billablehours * e.Billing_Rate
FROM HumanResources.Employees e
WHERE e.Employee_ID = @empid
之后,您创建一个计算列
ALTER TABLE ProjectDetails.TimeCards
ADD Total_Cost AS GetValue(Billable_hours, Employee_ID)
推荐阅读
- grafana - 有没有办法强制 Grafana 中的 Stat 面板的输出只显示天数
- html - 导航栏不显示项目
- oop - 如何使不是其抽象类的子类的接口实现者表现得像该接口的抽象类?
- javascript - 仅使用 JavaScript(无 PHP 或服务器端)创建基本登录/注册系统?
- python - 分类报告
- java - 使用 java 从 .xlsx 文件中读取特定信息
- elasticsearch - 使用 Elasticsearch Sink Connector for Kafka 从两个由下划线分隔的值字段创建文档 ID
- c# - 高圈复杂度会影响构建时间吗?
- android - Android 或 iOS 应用程序能否确定其主机设备是否由移动设备管理 (MDM) 解决方案配置?
- excel - 单击复选框仅适用于第一个实例 VBA Selenium(元素单击被拦截)