SQL查询 - 选择联合的计数

时间:2016-05-12 16:39:37

标签: sql sql-server count union

很抱歉打扰你但是我的工会数量有问题;我尝试实现我在其他帖子中读到的相同逻辑,但它不能为我工作,请帮忙吗?

这是我的代码: / 数据声明

/*where i should make the count*/

/*first select*/

UNION

/*second select*/
/*in the where of the second select I have a case with the following data*/
 CASE
    WHEN ((@case='other') AND (cfv.value like '%,' + cast (@today as VARCHAR) or cfv.value like '%' + cast    (@today as VARCHAR) 
    or cfv.value like '%' + cast (@today as VARCHAR)+',0'
    or cfv.value like '%' + cast (@today as VARCHAR)+',0,1'
    or cfv.value like '%' + cast (@today as VARCHAR)+',1'))
    then 1
    WHEN ((@case ='zero') AND(cfv.value='0')) THEN 1
    WHEN ((@case ='one') AND(cfv.value='1' or cfv.value='0,1')) THEN 1
    ELSE 0
END = 1

这个结果没有计算,所以我想这应该很容易,但我不明白:S Just a column of elements but I'd like to have the number of the element present in this case 2

非常感谢

3 个答案:

答案 0 :(得分:1)

如果您正在尝试计算所有选定的记录,您可以这样做:

SELECT COUNT(*) FROM
(
    SELECT First...
    UNION
    SELECT Second...
) AS CountTable

将整个查询包装在另一个SELECT语句中并从那里开始计数。

答案 1 :(得分:1)

在你的位置有一个case语句不应该弄乱语法。它可能是别的东西。

确保在执行子查询时为其提供别名。

SELECT COUNT(*)
FROM (
    /*first select*/
    UNION
    /*second select*/
    WHERE
    CASE
      WHEN ((@case='other') 
            AND (cfv.value LIKE '%,' + CAST(@today AS VARCHAR)
                 OR cfv.value LIKE '%' + CAST(@today AS VARCHAR) 
                 OR cfv.value LIKE '%' + CAST(@today AS VARCHAR)+',0'
                 OR cfv.value LIKE '%' + CAST(@today AS VARCHAR)+',0,1'
                 OR cfv.value LIKE '%' + CAST(@today AS VARCHAR)+',1'))
      THEN 1
      WHEN ((@case ='zero') AND (cfv.value='0')) THEN 1
      WHEN ((@case ='one') AND  (cfv.value='1' OR cfv.value='0,1')) THEN 1
      ELSE 0
    END = 1
) AS alias --<<--

答案 2 :(得分:0)

您可以尝试将其包装在选择中。

SELECT t.CompanyID, COUNT(*)
FROM (YOUR UNION QUERY) t
GROUP BY t.CompanyID