-2

假设我有 2 张桌子

销售

ProductName    SellingDate    ProductID   
iPhone 4G      2011-05-11     1
iPhone 4S      2011-05-12     2
iPhone 4S      2011-05-13     2
iPhone 4G      2011-05-15     1

购买

ProductName    BuyingDate    ProductID   
iPhone 4S      2011-05-09     2
iPhone 4G      2011-05-10     1
iPhone 4G      2011-05-13     1
iPhone 4G      2011-05-14     1    

如何将这个日期组合成这样?

ProductName    Date          Status      ProductID   
iPhone 4G      2011-05-10    Buying      1
iPhone 4G      2011-05-11    Selling     1
iPhone 4G      2011-05-13    Buying      1
iPhone 4G      2011-05-14    Buying      1
iPhone 4G      2011-05-15    Selling     1

我不知道如何将 2 个表日期(SellingDate/BuyingDate)组合成 1 个表(日期)...

任何帮助,将不胜感激!!

4

1 回答 1

1

我假设您所需的输出与您给定的输入不匹配,因此如果这只是组合两个表的情况, aUNION ALL应该就足够了。

SELECT ProductName, Date, 'Buying' AS Status, ProductID FROM Buying
UNION ALL SELECT ProductName, Date, 'Selling' AS Status, ProductID FROM Selling

您可以使用以下内容添加用户可选择的 productid

SELECT ProductName, Date, 'Buying' AS Status, ProductID FROM Buying WHERE ProductID = 1
UNION ALL SELECT ProductName, Date, 'Selling' AS Status, ProductID FROM Selling WHERE ProductID = 1

或这个

SELECT * 
FROM   (
         SELECT ProductName, Date, 'Buying' AS Status, ProductID FROM Buying
         UNION ALL SELECT ProductName, Date, 'Selling' AS Status, ProductID FROM Selling
       ) p
WHERE   ProductID = 1

如果您确实需要给定输入的这些输出,则必须向我们提供一些附加信息

  1. ProductID 2 发生了什么?
  2. iPhone 4S系列怎么了?
  3. 为什么不保留这些?

作为旁注和供将来参考,请尽可能准确和完整。我假设您的反对意见是您的输出与您的输入不匹配的结果。

于 2012-05-13T12:05:18.737 回答