根据单个列中的多个条件选择多个列
Posted
技术标签:
【中文标题】根据单个列中的多个条件选择多个列【英文标题】:Select multiple columns based on multiple conditions from single column 【发布时间】:2021-12-11 06:02:44 【问题描述】:我在数据库中有一个表,其中存储了金额、它们各自的“发票日期”以及这些发票日期属于合同的哪一年。
有签订年度、半年度、季度和月度合同的客户。因此,一年可以有多个发票 - 因此该列定义发票属于哪一年。
看起来类似这样:
ContractID | InvoiceNumber | InvoiceDate | Amount | YearIndex |
---|---|---|---|---|
1 | 1 | 01/01/2019 | 100 | 1 |
1 | 2 | 01/06/2019 | 100 | 1 |
1 | 3 | 01/01/2020 | 100 | 2 |
1 | 4 | 01/06/2020 | 100 | 2 |
2 | 1 | 01/03/2020 | 200 | 1 |
2 | 2 | 01/03/2020 | 200 | 2 |
2 | 3 | 01/03/2021 | 200 | 3 |
3 | 1 | 01/01/2020 | 300 | 1 |
3 | 2 | 01/04/2020 | 300 | 1 |
3 | 3 | 01/07/2020 | 300 | 1 |
3 | 4 | 01/10/2020 | 300 | 1 |
理想情况下,我想运行一个查询,在那里我可以看到每个合同金额的总和,按年份索引分组,例如
ContractID | Year1Amount | Year2Amount | Year3Amount |
---|---|---|---|
1 | 200 | 200 | NULL |
2 | 200 | 200 | 200 |
3 | 1200 | NULL | NULL |
这可能来自单个查询吗?还是需要加入多个?
关于可用语法,我正在使用 Microsoft Access。
提前感谢您的帮助。
【问题讨论】:
【参考方案1】:这是一般模式。您可以根据需要切换 Access 和 Null 与 0 的语法。
SELECT ContractID,
SUM(CASE WHEN YearIndex = 1 THEN Amount ELSE 0 END) AS Year1Amount,
SUM(CASE WHEN YearIndex = 2 THEN Amount ELSE 0 END) AS Year2Amount,
...
SUM(CASE WHEN YearIndex = N THEN Amount ELSE 0 END) AS YearNAmount
FROM SOME_TABLE
GROUP
BY ContactID
【讨论】:
非常感谢,完全忘记了凯斯。【参考方案2】:数据库不想在并排显示中给你总和......你会创造很多复杂性来实现这一点
现成的有:
groupID groupYear sumAmount
特别是使用 Access 时,使用一种称为聚合查询的通用功能,您可以在网上找到相关教程
【讨论】:
【参考方案3】:只是想补充一下,Microsoft access 不支持 CASE 语句,仅支持 IIF 语句,但是,IIF 语句不允许在其中使用聚合函数。所以答案最终是以下访问:
SELECT
DISTINCT (ContractInvoiceInfo.ContractID),
Y1.Y1Amount,
Y2.Y2Amount,
Y3.Y3Amount,
Y4.Y4Amount,
Y5.Y5Amount
FROM
ContractInvoiceInfo INNER JOIN (
(
SELECT ContractID, SUM(Amount) AS Y1Amount
FROM ContractInvoiceInfo
WHERE YearIndex = 1
GROUP BY ContractID
) AS Y1 LEFT JOIN (
(
SELECT ContractID, SUM(Amount) AS Y2Amount
FROM ContractInvoiceInfo
WHERE YearIndex = 2
GROUP BY ContractID
) AS Y2 LEFT JOIN (
(
SELECT ContractID, SUM(Amount) AS Y3Amount
FROM ContractInvoiceInfo
WHERE YearIndex = 3
GROUP BY ContractID
) AS Y3 LEFT JOIN (
(
SELECT ContractID, SUM(Amount) AS Y4Amount
FROM ContractInvoiceInfo
WHERE YearIndex = 4
GROUP BY ContractID
) AS Y4 LEFT JOIN (
SELECT ContractID, SUM(Amount) AS Y5Amount
FROM ContractInvoiceInfo
WHERE YearIndex = 5
GROUP BY ContractID
) AS Y5
ON Y5.ContractID = Y4.ContractID)
ON Y4.ContractID = Y3.ContractID)
ON Y3.ContractID = Y2.ContractID)
ON Y2.ContractID = Y1.ContractID)
ON Y1.ContractID = ContractInvoiceInfo.ContractID
ORDER BY
ContractInvoiceInfo.ContractID;
【讨论】:
交叉表查询可能更简单。以上是关于根据单个列中的多个条件选择多个列的主要内容,如果未能解决你的问题,请参考以下文章