使用两个现有表中的数据创建新表

时间:2014-12-05 17:10:50

标签: sql sql-server

过去几天我一直在努力解决这个问题,而我所做的一切似乎都不起作用。任何帮助将非常感谢。这是一个家庭作业的问题,但我现在已经绞尽脑汁待了3天,我的教授一直都是ZERO的帮助。

我的困境是我正在尝试使用Columns创建一个全新的表,以及来自两个现有表的行。

问题如下:

  

使用AP数据库,创建一个名为“Invoices2Qtr2012”的新表,用于捕获供应商和   2012年第二季度的发票数据,用于发票和发票中的以下属性   供应商表:VendorName,InvoiceNumber,InvoiceTotal,InvoiceDueDate,PaymentDate。

     

此外,添加一个新列,显示每个发票付款是按时还是晚,以及   另一个新列,显示哪个供应商每个月的发票最多。这个   应该只包括2012年第二季度的数据。

以下是表格的结构:

发票:

InvoiceId
VendorID
InvoiceNumber
InvoiceDate
InvoiceTotal
PaymentTotal
CreditTotal
TermsID
InvoiceDue
PaymentDate

供应商:

VendorID
VendorName
VendorAddress1
VendorAddress2
VendorCity
VendorState
VendorZipCode
VendorPhone
VendorContactLName
VendorContactFName
DefaultTermsID
DefaultAccountNo

以下是我目前为止的代码:

CREATE TABLE Invoices2Qtr2012 AS
SELECT VendorName, InvoiceNumber, InvoiceTotal, InvoiceDueDate, PaymentDate
FROM Invoices, Vendors
WHERE InvoiceDate BETWEEN '2012-03-31' AND '2012-07-01'

2 个答案:

答案 0 :(得分:0)

我确信它可以减少到更少的陈述,它可能无法100%工作,但也许这可以让你开始或至少给你一些想法:

CREATE TABLE Invoices2Qtr2012 AS
SELECT VendorName, InvoiceNumber, InvoiceTotal, InvoiceDueDate, PaymentDate, InvoiceDate
FROM Invoices, Vendors
WHERE InvoiceDate BETWEEN '2012-03-31' AND '2012-07-01'

ALTER TABLE Invoices2Qtr2012
ADD LateOnTime varchar(255) DEFAULT 'On time'
ADD LargestInvoicePerMonth varchar(255) DEFAULT 'Not Largest'

UPDATE Invoices2Qtr2012
SET LateOnTime = 'Late'
WHERE PaymentDate > InvoiceDueDate;

UPDATE Invoices2Qtr2012
SET LargestInvoicePerMonth = 'Largest for April'
WHERE InvoiceTotal >= ALL (SELECT InvoiceTotal FROM Invoices2Qtr2012 WHERE InvoiceDate BETWEEN '2012-03-31' AND '2012-05-01')

UPDATE Invoices2Qtr2012
SET LargestInvoicePerMonth = 'Largest for May'
WHERE InvoiceTotal >= ALL (SELECT InvoiceTotal FROM Invoices2Qtr2012 WHERE InvoiceDate BETWEEN '2012-04-31' AND '2012-06-01')

UPDATE Invoices2Qtr2012
SET LargestInvoicePerMonth = 'Largest for June'
WHERE InvoiceTotal >= ALL (SELECT InvoiceTotal FROM Invoices2Qtr2012 WHERE InvoiceDate BETWEEN '2012-05-31' AND '2012-07-01')

答案 1 :(得分:-1)

SELECT INTO语句将为您创建表。所以你的代码将是:

SELECT INTO Invoices2Qtr2012  VendorName, InvoiceNumber, InvoiceTotal, InvoiceDueDate, PaymentDate
FROM Invoices, Vendors
WHERE InvoiceDate BETWEEN '2012-03-31' AND '2012-07-01'

在此之后,我建议创建适当的索引,键和约束。

表Invoices2Qtr2012必须不存在。