0
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;

Where the types are "a" and "b". My query will return:

ID         First of Type         Count of I
1          a                     6

This is great but what I'd like is:

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

I can't figure out how to make this work. Any help would be much appreciated!

EDIT:

I'm doing this in Access. My tables look like:

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

And I want to return

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

Hope this makes sense. I tried to use the "union all" syntax but no luck with what I'm trying so far.

4

2 回答 2

0

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

[A query]
union all
[another query]

例如

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;
于 2013-07-22T14:58:32.017 回答
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,并没有真正允许枢轴查询,这似乎是您正在寻找的。我建议调查枢轴查询。

于 2013-07-22T15:22:02.120 回答