[英]Select Distinct Values, Pass Into Where Clause
I am trying to look at unique values in my table, and based on n number of values returned from the distinct query, pass those into a subsequent query in my WHERE clause. 我试图查看表中的唯一值,并基于从不同查询返回的n个值,将这些值传递到WHERE子句中的后续查询中。
Let me provide an example. 让我提供一个例子。
I have the a Table with the following columns: 我有一个包含以下列的表格:
ID | UserName | OtherCondition
I usually compute the total records, those which match a WHERE clause on OtherCondition , and their related percentages, as such: 我通常会计算总记录,与OtherCondition上的WHERE子句匹配的记录及其相关百分比,如下所示:
SELECT 'Report' as ReportName,
COUNT(*) Match,
(SELECT COUNT(*) FROM [MyTable) Total,
CAST(COUNT(*) AS FLOAT)/CAST((SELECT COUNT(*) FROM [MyTable]) AS FLOAT)*100 Percentage
FROM [MyTable]
WHERE OtherCondition = MyCondition
Now, I am trying to integrate the UserName column into this query. 现在,我正在尝试将UserName列集成到此查询中。 By this I mean, what would happen is I look through the above table, and get all the unique usernames for all records (this can potentially be empty/null as well). 我的意思是,我将浏览上表,并获取所有记录的所有唯一用户名(这也可能为空/空)。 This username would be passed into ReportName (currently a string literal) in the above (in the format of something like 'Report - ' [username]), and this would also be passed into a second WHERE condition. 该用户名将被传递给上面的ReportName (当前为字符串文字)(格式为'Report-'[username]),并且还将被传递给第二个WHERE条件。 In totality, the WHERE condition would then look like: 总体而言,WHERE条件如下所示:
WHERE OtherCondition = MyCondition AND UserName = [The Passed in unique username, from the not yet defined query]
Essentially, this would allow me to find all the unique users, and provide user based reporting. 从本质上讲,这将使我能够找到所有唯一用户,并提供基于用户的报告。
Some sample data: 一些样本数据:
ID | UserName | OtherCondition
1 Mary X
2 John X
3 Mary X
Expected Results: 预期成绩:
SELECT 'Report - Mary' as ReportName,
COUNT(*) Match,
(SELECT COUNT(*) FROM [MyTable) Total,
CAST(COUNT(*) AS FLOAT)/CAST((SELECT COUNT(*) FROM [MyTable]) AS FLOAT)*100 Percentage
FROM [MyTable]
WHERE OtherCondition = x AND UserName = 'Mary'
SELECT 'Report - John' as ReportName,
COUNT(*) Match,
(SELECT COUNT(*) FROM [MyTable) Total,
CAST(COUNT(*) AS FLOAT)/CAST((SELECT COUNT(*) FROM [MyTable]) AS FLOAT)*100 Percentage
FROM [MyTable]
WHERE OtherCondition = x AND UserName = 'John'
It hope that I understood what you want: 希望我了解您想要什么:
SELECT ('Report - '+ UserName) as ReportName,
COUNT(*) Match, (SELECT COUNT(*) FROM [MyTable]) Total,
CAST(COUNT(*) AS FLOAT) /
CAST((SELECT COUNT(*) FROM [MyTable]) AS FLOAT)*100 Percentage
FROM [MyTable]
WHERE OtherCondition = x
GROUP BY UserName;
This query delivers the output of the two last queries of your post. 此查询提供帖子的最后两个查询的输出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.