sql server 2视图合二为一

时间:2011-03-21 10:36:54

标签: sql sql-server ssrs-2008

我有3种不同的观点

  1. select count(*) as Grandtotal from table x where id=1
  2. select count(*) as total from table x where id=1 and [bla bla] Group by id
  3. select top1(a) from table y
  4. 我需要创建包含流动列的视图

    GrandTotal,total,a

3 个答案:

答案 0 :(得分:3)

SELECT
  COUNT(*) AS GrandTotal,
  COUNT(CASE WHEN [bla bla] THEN 1 END) AS Total
  (SELECT TOP 1 a FROM y) AS a
FROM x
WHERE id = 1

答案 1 :(得分:1)

使用case,您还可以在单​​个查询中组合选择:

select  sum(case when id=1 then 1 end) as Id1GrandTotal
,       count(distinct case when id=1 and [bla bla] then id end) 
            as Id1AndBlahBlahExists
,       max(a) as TopValueOFA
from    TableY

答案 2 :(得分:0)

SELECT
 (SELECT Count(*) FROM table x WHERE id = 1) AS GrandTotal,
 (SELECT Count(*) FROM table WHERE id = 1 AND ...) AS Total,
 (SELECT TOP 1 fieldname FROM table ...) AS a

应该可以工作,但您可能必须加入虚拟表才能获得某些数据库的信息

e.g。

SELECT 
 ...
FROM numbers_table n WHERE n.num = 1