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.
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:
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. 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. In totality, the WHERE condition would then look like:
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.