多次查询导致出现次数最少

时间:2019-02-18 08:20:46

标签: sql sql-server

我需要根据exp_condition查找任何主题检索到的文档数量最少。主题表中的Exp_condition包含“ 1”和“ 2”列。

以下是表格: 主题表:

+-----------------+--------------+
| Field           | Type         |
+-----------------+--------------+
| username        | varchar(255) |
| user_type       | varchar(10)  |
| years           | int          |
| low_grade       | int          |
| high_grade      | int          |
| on_line         | varchar(10)  |
| on_line_sources | varchar(255) |
| location        | varchar(5)   |
| exp_condition   | int          |
+-----------------+--------------+
tasks table:

+------------+--------------+
| Field      | Type         |
+------------+--------------+
| username   | varchar(255) |
| task       | varchar(5)   |
| confidence | int          |
| sim_helpd  | int          |
+------------+--------------+

docs表:

+--------------+--------------+
| Field        | Type         |
+--------------+--------------+
| username     | varchar(255) |
| task         | varchar(5)   |
| doc_type     | varchar(10)  |
| used_tool    | int          |
| relevant     | int          |
| motivational | int          |
| concepts     | int          |
| background   | int          |
| grade_level  | int          |
| hands_on     | int          |
| attachments  | int          |
+--------------+--------------+

我能够为两个exp_condition值生成主题数和文档数。我可以使用多个查询,但不确定如何使用。

用于生成条件1和2的主题数的代码。

select count(distinct(t2.username)) 
from tasks as t1 
inner join subjects as t2 
on t1.username = t2.username group by exp_condition;

用于为exp_condition 1和2生成文档数量的代码

select count(*), exp_condition 
from docs as t1 
left join subjects as t2 
on t1.username = t2.username 
group by exp_condition;

预期输出:两个单独的数字,表示任何主题根据exp_condition检索到的最小文档数。

谢谢。

1 个答案:

答案 0 :(得分:1)

您可以使用子查询或CTE

SubQuery

SELECT exp_condition, MIN(A) as Tasks, MIN(B) as Docs FROM (
    SELECT exp_condition, COUNT(DISTINCT t2.username) A, COUNT(DISTINCT (t3.username) B
    FROM subjects s
    LEFT JOIN tasks T2 ON s.username = t2.username
    LEFT JOIN docs T3 ON s.username = t3.username
    GROUP BY exp_condition
) A
GROUP BY ex_condition 

CTE

;WITH CTE AS (
    SELECT exp_condition, COUNT(DISTINCT t2.username) A, COUNT(DISTINCT (t3.username) B
        FROM subjects s
        LEFT JOIN tasks T2 ON s.username = t2.username
        LEFT JOIN docs T3 ON s.username = t3.username
        GROUP BY exp_condition
)
SELECT exp_condition, MIN(A) as Tasks, MIN(B) as Docs 
FROM CTE 
GROUP BY ex_condition