我正在为我公司的Access DB工作,我有一个包含这些列的表:
共同名称项目 - 名称日期1日期2日期3日期4日期5日期6日期7日期8付款1付款2付款3付款4付款5付款6付款7付款8付款1代理商Deatil3代理商Deatil4代理商Deatil6代表Deatil7 Deatil8
我想设计一个包含以下列的查询:
日期(用户可以输入范围) SUM [此期间的付款总和] 共同的名字 项目名称
任何人都可以在此查询中帮助我吗?
答案 0 :(得分:1)
您的问题的答案是规范化。您当前的设置不会以任何可能的方式帮助您。相当复杂。
您应该拥有行,而不是拥有列。所以TOTALS查询可以发挥它的魔力。设置应该是,
Co-Name | Project-Name | DateOfPay | Payment | Details
而不是设置这个,
Co-Name | ProjName | Date1 | Payment1| Detail1 | Date2 | Payment2| Detail2 | Date3 | Payment3| Detail3
--------+---------------+-----------+-----------+-----------+-----------+-----------+-----------+-----------+-----------+-------------
AAA | X-1 |22/05/2014 | £ 500 | First |27/07/2014 | £ 100 | Second | | |
BBB | Y-1 |02/08/2014 | £ 300 | First |15/09/2014 | £ 250 | Second |24/10/2014 | £ 400 | Third
CCC | X-1 |07/11/2014 | £ 100 | First | | | | | |
您应该将设置设为,
Co-Name | Project-Name | DateOfPay | Payment | Details
--------+-------------------+---------------+-----------+-------------
AAA | X-1 | 22/05/2014 | £ 500 | First
AAA | X-1 | 27/07/2014 | £ 100 | Second
BBB | Y-1 | 02/08/2014 | £ 300 | First
BBB | Y-1 | 15/09/2014 | £ 250 | Second
BBB | Y-1 | 24/10/2014 | £ 400 | Third
CCC | Z-1 | 07/11/2014 | £ 100 | First
这样,您的代码就像
一样简单SELECT
[Co-Name],
[Project-Name],
Sum(Payment) As TotalPaid
FROM
theProperTable
WHERE
DateOfPay BETWEEN [EnterTheStartDate:] And [EnterTheEndDate:]
GROUP BY
[Co-Name],
[Project-Name]
答案 1 :(得分:0)
如果您无法更改表格的结构,可以通过创建一个返回"标准化"的查询来伪造它。表格的版本。将此SQL保存为名为ProjectsNormalized:
的查询 (SELECT [Co-Name], [Project-Name], Date1 As DateOfPay, Payment1 As Payment, Detail1 As Details FROM Projects WHERE Date1 Is Not Null;)
UNION ALL
(SELECT [Co-Name], [Project-Name], Date2 As DateOfPay, Payment2 As Payment, Detail2 As Details FROM Projects WHERE Date2 Is Not Null;)
UNION ALL
(SELECT [Co-Name], [Project-Name], Date3 As DateOfPay, Payment3 As Payment, Detail3 As Details FROM Projects WHERE Date3 Is Not Null;)
UNION ALL
(SELECT [Co-Name], [Project-Name], Date4 As DateOfPay, Payment4 As Payment, Detail4 As Details FROM Projects WHERE Date4 Is Not Null;);
如果项目包含此数据:
然后ProjectsNormalized将为您提供此数据:
现在你可以对ProjectsNormalized进行查询,就像它是一个表一样。
注意:使用UNION ALL而不仅仅是UNION很重要,因为UNION会丢弃重复记录。如果您在同一天有两个相同的付款并且具有相同的详细信息,则您希望报告它们。