SQL:在同一个表上组合四个“where”子句

时间:2012-04-26 15:53:07

标签: sql ms-access

我正在努力让这个工作起作用。

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 个答案:

答案 0 :(得分:3)

SELECT      Y, C, SUM(N) 'Sum'
FROM        stat
WHERE       C IN ( 'Denmark', 'Finland', 'Norway', 'Sweden' )
GROUP BY    Y, C

答案 1 :(得分: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

答案 2 :(得分: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

答案 3 :(得分:0)

最好的猜测 - 使用TRANSFORM

,我没有方便尝试使用Access
TRANSFORM SUM(N)
  SELECT Y FROM STAT
  GROUP BY Y
  ORDER BY Y
  PIVOT C