2

我目前正在努力让它发挥作用。

SELECT        Y, SUM(N) AS sumDK, NULL AS sumFI, NULL AS sumNO, NULL AS sumSE
FROM            stat
WHERE        (C = 'Denmark')
GROUP BY Y
UNION ALL
SELECT        Y, NULL AS sumDK, SUM(N) AS sumFI, NULL AS sumNO, NULL AS sumSE
FROM            stat
WHERE        (C = 'Finland')
GROUP BY Y
UNION ALL
SELECT        Y, NULL AS sumDK, NULL AS sumFI, SUM(N) AS sumNO, NULL AS sumSE
FROM            stat
WHERE        (C = 'Norway')
GROUP BY Y
UNION ALL
SELECT        Y, NULL AS sumDK, NULL AS sumFI, NULL AS sumNO, SUM(N) AS sumSE
FROM            stat
WHERE        (C = 'Sweden')
GROUP BY Y

这个查询给了我一个像这样的矩阵:

Y | sumDK | sumFI | sumNO | sumSE
----------------------------------
2011| 25 | NULL | NULL | NULL 
2012| 5 | NULL | NULL | NULL 
2011| NULL | 18 | NULL |NULL 
2012| NULL | 5 | NULL |NULL 
......

如何执行只返回字段 NOT NULL 的查询?提前致谢!

4

4 回答 4

3
SELECT      Y, C, SUM(N) 'Sum'
FROM        stat
WHERE       C IN ( 'Denmark', 'Finland', 'Norway', 'Sweden' )
GROUP BY    Y, C
于 2012-04-26T15:58:42.600 回答
1

遍历表一次,并通过对各列的匹配求和将其创建为交叉表

select
      Y,
      SUM( IIF( C = 'Denmark', N, 0 )) as SumDenmark,
      SUM( IIF( C = 'Finland', N, 0 )) as SumFinland,
      SUM( IIF( C = 'Norway', N, 0 )) as SumNorway,
      SUM( IIF( C = 'Sweden', N, 0 )) as SumSweden,
      sum( N ) totalSumValue,
      count(*) totalEntries
   FROM 
      STAT
   WHERE
      C IN ( 'Denmark', 'Finland', 'Norway', 'Sweden' )
  GROUP BY 
      Y
于 2012-04-26T16:08:43.980 回答
0

是否有必要以不同的方式命名它们?关于什么

SELECT        Y, SUM(N) AS sum, C
FROM            stat
WHERE        (C = 'Denmark')
GROUP BY Y
UNION ALL
SELECT        Y, SUM(N) AS sum, C
FROM            stat
WHERE        (C = 'Finland')
GROUP BY Y
UNION ALL
SELECT        Y, SUM(N) AS sum, C
FROM            stat
WHERE        (C = 'Norway')
GROUP BY Y
UNION ALL
SELECT        Y, SUM(N) AS sum, C
FROM            stat
WHERE        (C = 'Sweden')
GROUP BY Y
于 2012-04-26T15:57:54.193 回答
0

最好的猜测 - 我没有 Access 方便尝试 - 使用TRANSFORM

TRANSFORM SUM(N)
  SELECT Y FROM STAT
  GROUP BY Y
  ORDER BY Y
  PIVOT C
于 2012-04-26T16:27:34.847 回答