SQL - 请整理我的查询

时间:2014-04-03 06:36:16

标签: sql sql-server

编辑:上下文是我正在使用reportviewer制作报告。它是第一个SELECT完美的发票(即客户名称和交货细节)。第二个SELECT用于拖欠本月初的欠款。欢迎使用替代方式(阅读'查询')来做到这一点。 附: (如果有人已经做过类似的工作,你的查询应该会有所帮助)

谢谢, 绝望现在

:编辑已关闭

SELECT delvoucher.dvdate, 
           delvoucher.dvno, 
           delvoucher.vehicleno, 
           delvoucher.salesman, 
           dvdetails.[desc], 
           dvdetails.supply, 
           dvdetails.empty, 
           dvdetails.amount, 
           dvdetails.rate, 
           delvoucher.title, 
           customer.currentaddress, 
           customer.phone, 
           customer.code
    FROM   delvoucher 
    INNER JOIN dvdetails ON delvoucher.id = dvdetails.pid 
    INNER JOIN customer ON delvoucher.title = customer.title
    WHERE YEAR(delvoucher.dvdate) = YEAR(@i) AND MONTH(delvoucher.dvdate) = MONTH(@i)
    UNION ALL
    (SELECT SUM(amount) - sum(recvd)
     FROM dvdetails 
     INNER JOIN delvoucher ON delvoucher.id = dvdetails.pid
     WHERE delvoucher.dvdate < DATEADD(month, 1, @i))

如果我删除UNION部件,它运行正常。工会部分给我特定客户的欠款,直到上个月。任何其他方式来获得客户的欠款余额

2 个答案:

答案 0 :(得分:1)

快速修复(但我不认为这是你想要的):

SELECT 
       0 as SUMPLACEHOLDER,
       delvoucher.dvdate, 
       delvoucher.dvno, 
       delvoucher.vehicleno, 
       delvoucher.salesman, 
       dvdetails.[desc], 
       dvdetails.supply, 
       dvdetails.empty, 
       dvdetails.amount, 
       dvdetails.rate, 
       delvoucher.title, 
       customer.currentaddress, 
       customer.phone, 
       customer.code
FROM   delvoucher 
INNER JOIN dvdetails ON delvoucher.id = dvdetails.pid 
INNER JOIN customer ON delvoucher.title = customer.title
WHERE YEAR(delvoucher.dvdate) = YEAR(@i) AND MONTH(delvoucher.dvdate) = MONTH(@i)
UNION ALL
(SELECT SUM(amount) - sum(recvd), null, null, null, null, null, null, null, null, null, null, null, null, null
 FROM dvdetails 
 INNER JOIN delvoucher ON delvoucher.id = dvdetails.pid
 WHERE delvoucher.dvdate < DATEADD(month, 1, @i))

答案 1 :(得分:0)

使用Union的第一个必要条件是,您的选择查询必须具有相同的列数,并且列的格式必须相同。在您的情况下,第二个选择查询只有1列,这肯定不起作用。您可以单独运行查询,也可以将第二个查询更改为具有相同数量的列和格式。