SQL:Query返回具有特定值的记录计数作为列

时间:2013-07-22 14:47:13

标签: sql ms-access

SELECT DISTINCTROW P.ID, First(I.Type) AS [First Of Type], Count(*) AS [Count Of I]
FROM P INNER JOIN I ON P.[ID] = I.[P ID]
GROUP BY P.ID;

其中类型为“a”和“b”。我的查询将返回:

ID         First of Type         Count of I
1          a                     6

这很棒,但我想要的是:

ID         First of Type         Count of I        Count of a        Count of b
1          a                     6                 2                 4

我无法弄清楚如何使这项工作。任何帮助将不胜感激!

编辑:

我在Access中这样做。我的表看起来像:

Table P
ID           Name
1            Alice
2            Bob


Table I
ID           P ID       Type
1            1          a
2            1          b
3            1          a
4            1          b
5            1          b
6            1          b
7            2          b

我想要回归

ID         First of Type         Count of I        Count of a        Count of b
1          a                     6                 2                 4
2          b                     1                 0                 1

希望这是有道理的。我尝试使用“union all”语法,但到目前为止我没有运气。

2 个答案:

答案 0 :(得分:0)

不是100%你的要求所以如果你能解释一下你想要什么会有所帮助,但想想你的目标是使用union all

[A query]
union all
[another query]

e.g。

SELECT DISTINCT ROW P.ID, First(I.Type) AS [First Of Type], Count(*) AS [Count Of I]
FROM P INNER JOIN I ON P.[ID] = I.[P ID]
GROUP BY P.ID 
union all
SELECT COUNT(*) AS ColumnA
FROM WHERE_EVER
WHERE A_CONDITION;

答案 1 :(得分:0)

我想你想要这样的东西:

SELECT 
    DISTINCTROW 
    P.ID, First(I.Type) AS [First Of Type], 
    Count(*) AS [Count Of I],
    SUM(CASE P.ID WHEN 1 THEN 1 ELSE 0 END) AS [Count of Alice],
    SUM(CASE P.ID WHEN 2 THEN 1 ELSE 0 END) AS [Count of Bob]
FROM 
    P INNER JOIN I ON P.[ID] = I.[P ID]
GROUP BY P.ID;

或具体访问使用它的人:

SELECT 
    DISTINCTROW 
    P.ID, First(I.Type) AS [First Of Type], 
    Count(*) AS [Count Of I],
    SUM(IIF (I.Type = "a", 1, 0)) AS [Count of a],
    SUM(IIF (I.Type = "b", 1, 0)) AS [Count of b]
FROM 
    P INNER JOIN I ON P.[ID] = I.[P ID]
GROUP BY P.ID;

当然,这只能涵盖Alice和Bob,并且实际上不允许使用数据透视查询,这就是您正在寻找的内容。我建议调查数据透视查询。