Sql在单个查询中从两个表中选择

时间:2014-09-10 19:44:48

标签: sql sql-server crystal-reports

我有

下的两个表格
        SalesDetails                          PurchaseDetails 
Date   SaleOrderId ProductId Qty       Date    PurcsOrderId ProductId    Qty 
2/2/12 S_1           P_1       4       1/2/12   PO_1          P_1       50
3/2/12 S_2           P_1       5       4/2/12   PO_2          P_1       50   
3/2/12 S_2           P_2       7       
6/2/12 S_3           P_1       3
9/2/12 S_4             1       5

from these two tables i want to show a report like this
         Product Inquiry Report 
             ProductId: P_1
Date     TrId Debit    Credit   
1/2/12   PO_1  50                
2/2/12   S_1            4   
3/2/12   S_2            5
4/2/12   PO_2  50   
6/2/12   S_3            3

此处购买细节的数量列变为'借记卡'在报告和SalesDetails中的数量成为' Credit'在Report.In报告中的列,该事务应该显示为Date,如图所示有没有办法在单个查询中执行此操作,如果是,那么如何?如果没有,那么还有其他解决方案吗?提前致谢

2 个答案:

答案 0 :(得分:3)

使用UNION:

SELECT Date, SaleOrderID as TrId, NULL as Debit, Qty as Credit 
FROM SalesDetails
UNION
SELECT Date, PurcsOrderId AS TrId, Qty AS Debit, NULL as Credit
FROM PurchaseDetails
ORDER BY Date

答案 1 :(得分:0)

SQL Fiddle

SELECT * 
FROM
(
  SELECT sa.Date, sa.SaleOrderId AS TRId, Null AS Debit, sa.Qty AS Credit
  FROM SalesDetails sa
  UNION
  SELECT pa.Date, pa.PurcsOrderId AS TRId, pa.Qty AS Debit, Null AS Credit
  FROM PurchaseDetails pa
) m
ORDER BY 1

如果您希望值为0,请分别使用0 AS Debit0 AS Credit

相关问题