分析SQL子查询

时间:2018-01-29 17:41:35

标签: sql sql-server

我有一个如下表格,并希望根据子查询执行分析,例如sql

select from Table1 where Value (Param.internal ) > Value Param.external.

Department,  Param,      Value
Dept1,      internal,     5
Dept1,      external,     6
Dept1,      others,       10
Dept2,      internal,     4
Dept2,      external,     3
Dept2,      others,       8
Dept3,      internal,     5
Dept3,      external,     5
Dept3,      others,       7

这不起作用:

SELECT * FROM Table1 
WHERE [Values] IN ( 
    SELECT [Value] 
    FROM Table1 
    WHERE Param= 'internal' > 
    SELECT [Value] 
    FROM Table1 WHERE Param= 'external'
    ) 

2 个答案:

答案 0 :(得分:2)

这没有用:

SELECT * 
FROM Table1 
WHERE [Values] IN (SELECT [Value] 
                   FROM Table1 
                   WHERE Param= 'internal' > SELECT [Value] FROM Table1 WHERE Param= 'external') 

我认为您正在尝试找到部门内部列更大的外部。

试试这个:

select Department
    ,sum(case when Param = 'internal' then Value else 0 end) as Internal
    ,sum(case when Param = 'external' then Value else 0 end) as External
    ,sum(case when Param = 'others' then Value else 0 end) as Others
    --Added based on comment
    , (SELECT COUNT(DISTINCT Department) from Table1) as CtDistinctDept
    ,sum(Value) as DeptTotal
from table1
group by department
--optional
having sum(case when Param = 'internal' then Value else 0 end)
      > sum(case when Param = 'external' then Value else 0 end)

答案 1 :(得分:2)

我会用EXISTS编写查询:

SELECT *
FROM Table1 t1
WHERE Param = 'internal'
AND EXISTS
(SELECT 1
 FROM Table1 t2
 WHERE Param = 'external'
 AND t1.Department = t2.Department
 AND t1.value > t2.value)

所以基本上返回所有行:

  1. Param =内部AND
  2. 还有另一行具有相同的部门名称,其中param = external,外部值小于内部值
  3. 根据您上面的示例数据,将返回第2部分。

    根据评论进行编辑: 如果要显示部门的所有行,您只需将上面的内容连接到主表,如下所示:

    SELECT main.*
    FROM Table1 main
    INNER JOIN
    (SELECT t1.Department
     FROM Table1 t1
     WHERE Param = 'internal'
     AND EXISTS
     (SELECT 1
      FROM Table1 t2
      WHERE Param = 'external'
      AND t1.Department = t2.Department
      AND t1.value > t2.value) sub
    ON main.Department = sub.Department