将列转换为行并在 Access 中获取复选框的总和

Posted

技术标签:

【中文标题】将列转换为行并在 Access 中获取复选框的总和【英文标题】:Convert columns to rows and get the sum of checkboxes in Access 【发布时间】:2020-11-06 17:19:09 【问题描述】:

我有一个 Access 数据库,其中的表中有复选框。我需要得到复选框的总和,但我想将复选框列转换为行而不是列。

下面是它在表格中的显示示例:

 Name         DND  Other  CAP   SAP   DAP   EXP
Person One    -1    -1    NULL  NULL  -1    -1
Person Two    NULL  -1    -1     -1   NULL  NULL
Person Three  NULL  -1    -1    NULL  NULL  NUll

这是我希望报告显示数据的方式:

 Discharge  Count
    DND        1
    Other      3
    CAP        2
    SAP        1
    DAP        1
    EXP        1

我尝试使用 Case 语句,但结果不正确

【问题讨论】:

【参考方案1】:

使用union query 并检查Null

Select 
    T.Discharge, Abs(Sum(T.[Count])) As DischargeCount
From 
    (Select "DND" As Discharge, [DND] Is Not Null As [Count] From YourTable
    Union ALL
    Select "Other" As Discharge, [Other] Is Not Null As [Count] From YourTable
    Union ALL
    Select "CAP" As Discharge, [CAP] Is Not Null As [Count] From YourTable
    Union ALL
    Select "SAP" As Discharge, [SAP] Is Not Null As [Count] From YourTable
    Union ALL
    Select "DAP" As Discharge, [DAP] Is Not Null As [Count] From YourTable
    Union ALL
    Select "EXP" As Discharge, [EXP] Is Not Null As [Count] From YourTable) As T
Group By
    T.Discharge

【讨论】:

谢谢。两者都很有帮助,但这更好。【参考方案2】:
SELECT 'DND' AS Discharge, COUNT(*) AS [Count] FROM tbl WHERE DND = -1
UNION ALL
SELECT 'Other' AS Discharge, COUNT(*) AS [Count] FROM tbl WHERE Other = -1
UNION ALL

等等

我认为没有更简单的方法。

这是航空代码,不确定是否需要GROUP BY 子句。

比较How to simulate UNPIVOT in Access?

【讨论】:

以上是关于将列转换为行并在 Access 中获取复选框的总和的主要内容,如果未能解决你的问题,请参考以下文章

sql 将列数据转换为行

将列值转换为行值

将列转换为行

SQL Server:将列转换为行

SQL Unpivot行并获取订单号

将数据从多列转换为行并保留“标签”