简体   繁体   English

SQL查询-选择的并集计数

[英]SQL query - Count of union of select

sorry to disturb you but I got a problem with a count of union; 抱歉打扰您,但我在工会方面遇到了问题; I try to implement the same logic that I read in other post but it's not working for me, some help please? 我尝试实现与我在其他帖子中阅读的相同的逻辑,但是它对我不起作用,请帮忙吗?

This is my code: / Declaration of data ? 这是我的代码:/ 数据声明

/*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

and this re result without count so I suppose that should be very easy but I don't get it :S Just a column of elements but I'd like to have the number of the element present in this case 2 结果不计其数,所以我想这应该很容易,但我不明白:S 仅是一列元素,但在这种情况下我想知道存在的元素数量2

Thanks so much in advance 提前非常感谢

If you're trying to get a count of all the records selected, you could do this: 如果您要对所有选定记录进行计数,则可以执行以下操作:

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

Just wrap your whole query in another SELECT statement and count from there. 只需将整个查询包装在另一个SELECT语句中,然后从那里开始计数。

Having a case statement in your where should not mess up the syntax. 在哪里有一个case语句应该不会弄乱语法。 It is probably something else. 这可能是另一回事。

Make sure when doing a subquery you give it an alias. 确保在执行子查询时给它一个别名。

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

You can try wrapping it in a select. 您可以尝试将其包装在一个选择中。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM