SQL UNION操作有问题

时间:2010-10-21 17:25:03

标签: sql ms-access coldfusion aggregate-functions

我有下表: alt text

我正在尝试创建一个返回一个返回三个字段的表的SQL查询: 年(ActionDate),内置计数(actiontype = 12),失去计数(actiontype =几个不同的) 基本上,ActionType是一个查找代码。所以,我会得到类似的东西:

       YEAR   CountofBuilt  CountofLost
        1905        30          18
        1929        12          99
        1940        60           1 
etc....

我认为这将需要两个与UNION放在一起的SELECT语句。 我在下面尝试了以下内容,但它只吐了两列(年份和countbuilt)。我的countLost字段没有出现

我的sql当前(MS Access):

SELECT tblHist.ActionDate, Count(tblHist.ActionDate) as countBuilt
FROM ...
WHERE ((tblHist.ActionType)=12)
GROUP BY tblHist.ActionDate
UNION
SELECT tblHist.ActionDate, Count(tblHist.ActionDate) as countLost
FROM ...
WHERE (((tblHist.ActionType)<>2) AND
((tblHist.ActionType)<>3))
GROUP BY tblHist.ActionDate;

2 个答案:

答案 0 :(得分:3)

使用:

  SELECT h.actiondate,
         SUM(IIF(h.actiontype = 12, 1, 0)) AS numBuilt,
         SUM(IIF(h.actiontype NOT IN (2,3), 1, 0)) AS numLost
    FROM tblHist h
GROUP BY h.actiondate

答案 1 :(得分:1)

您不应该使用UNION进行此类查询。例如,有很多方法可以做你想做的事  已更新以符合访问语法

SELECT tblHist.ActionDate,
COUNT(SWITCH(tblHist.ActionType = 12,1)) as countBuilt,
COUNT(SWITCH(tblHist.ActionType <>1 OR tblHist.ActionType <>2 OR ...,1)) as countLost
FROM ..
WHERE ....
GROUP BY tblHist.ActionDate