简体   繁体   English

如何两次输出相同的列,受不同的 WHERE 子句和 COUNT 函数的影响

[英]How to output the same column twice, effected by different WHERE clauses with the COUNT function

I need to output one column twice, under different conditions and aliases.我需要在不同的条件和别名下两次输出一列。 Note: this column is also the PKEY of each table I pull from注:这一列也是我拉取的每张表的PKEY

For simplicity, lets say the column i want to output twice is called COL1为简单起见,假设我想输出两次的列称为 COL1

-The first version of COL1 I want to output contains rows where COL1 is a unique value Lets call this "UniqueCol1" -我想输出的第一个 COL1 版本包含 COL1 是唯一值的行 让我们称之为“UniqueCol1”

-The second version of COL1 I want to output contains rows where COL1 occurs more than once in the data set Lets call this "NonUniqueCol1" -我想输出的 COL1 的第二个版本包含在数据集中出现不止一次 COL1 的行让我们称之为“NonUniqueCol1”

The part of my query that's giving me trouble is that a bunch of other different conditions need to be true for each version of COL1, joins are involved, and I don't know exactly where to input the COUNT conditions that I believe I need.我的查询中给我带来麻烦的部分是,对于每个版本的 COL1,许多其他不同的条件都需要为真,涉及连接,而且我不知道在哪里输入我认为需要的 COUNT 条件。

The code I dropped below is essentially the query I have now.我放在下面的代码本质上是我现在的查询。

Select T1.COL2, T1.COL3, count(T1.COL3) as Counted
FROM table1 T1
INNER JOIN table2 T2
ON T1.COL1 = T2.COL1
AND T1.COL2 = T2.COL2
AND T1.COL3 = T2.COL3
WHERE EXISTS 
(
Select 1 
FROM
table2 TT2
inner join table1 TT1
ON TT2.COL1 = TT1.COL1
WHERE TT2.COL4 ='A'
AND TT2.COL5 ='3'
AND TT2.COL6 <> '55555555'
AND TT1.COL7 = 'M'
AND TT2.COL2 = T1.COL2
AND TT2.COL3 = T1.COL3

)
Group BY T1.COL2, T1.COL3
HAVING count(T1.COL2) >=3;

The result of this query is something like this:这个查询的结果是这样的:

COL2      COL3       Counted
C0067     4355       3
D8120     5777       4
C4444     9009       3
TBC09     1133       3
C0999     4617       3

Out of those entries Counted in COL3, there are two different COL1's在 COL3 中计算的这些条目中,有两个不同的 COL1

  1. The unique COL1 value独特的 COL1 值

  2. The COL1 value that shows up more than once多次出现的 COL1 值

My desired result is to print COL2, COL3, UniqueCOL1, and NonUniqueCOL1

Thank you for reading, help would be so much appreciated as SQL is not my strong-suit.感谢您的阅读,非常感谢您的帮助,因为 SQL 不是我的强项。

I'm not sure you have explained what you are wanting to achieve very well, but here is some code that might help, or might not.我不确定您是否已经很好地解释了您想要实现的目标,但这里有一些代码可能会有所帮助,也可能不会。

WITH table1(col1, col2, col3) AS (values ('x','a','a'), ('x','a','a'),('y','a','a'), ('z','a','a'),(null,'a','a'),('x','b','a'),('x','b','a'))
SELECT
    T1.COL2
,   T1.COL3
,   count(T1.COL1)          as NonUniqueCOL1
,   count(DISTINCT T1.COL1) as UniqueCOL1
FROM table1 T1
GROUP BY
    COL2, COL3

with returns有回报

COL2 |COL3 |NONUNIQUECOL1 |UNIQUECOL1 |
-----|-----|--------------|-----------|
a    |a    |4             |3          |
b    |a    |2             |1          |

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

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