我正在尝试查看表中的唯一值,并根据从不同查询返回的n个值,将这些值传递到 WHERE 子句中的后续查询中。
让我举个例子。
我有一个包含以下列的表:
ID | UserName | 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
现在,我正在尝试将UserName列集成到此查询中。我的意思是,我将通过上面的表格查看并获取所有记录的所有唯一用户名(这也可能是空/空)。此用户名将在上面传递给 ReportName (目前是字符串文字)(格式为'报告 - ' [用户名]),这也是传递到第二个WHERE条件。总体而言,WHERE条件将如下所示:
WHERE OtherCondition = MyCondition AND UserName = [The Passed in unique username, from the not yet defined query]
基本上,这将允许我找到所有唯一用户,并提供基于用户的报告。
一些示例数据:
ID | UserName | OtherCondition
1 Mary X
2 John X
3 Mary X
预期结果:
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'
答案 0 :(得分:1)
希望我理解你想要的东西:
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;
此查询提供帖子最后两个查询的输出。