9

我有一个tableA不同的价值观:

 data
------
 10
 15
 20
 40
 40000
 50000
 60000

此外,我需要获取有关该数据的一些统计信息(我想在一个查询中完成),例如:

select count(data) from tableA where data < 100
union all
select count(data) from tableA  where data >= 100

结果,我收到

(No column name)
----------------
4
3

但我想连续收到结果,如下所示:

Small | Big
---------
4     | 3 

怎么做?是否可以?

4

4 回答 4

11

尝试子查询而不是UNION ALL这样:

SELECT
  (SELECT COUNT(data) FROM tableA WHERE data < 100) AS Small,
  (SELECT COUNT(data) FROM tableA WHERE data >= 100) AS Big

看到这个 SQLFiddle

于 2012-09-18T05:13:01.977 回答
11
select count(case when data < 100 then 1 end) as Small,
       count(case when data >= 100 then 1 end) as Big
from TableA

平均而言,它看起来像这样。

select avg(case when data < 100 then data end) as Small,
       avg(case when data >= 100 then data end) as Big
from TableA
于 2012-09-18T05:16:28.477 回答
6
DECLARE @tst TABLE (
   val INT

)

INSERT INTO @tst (val)
SELECT 10
UNION
SELEcT 15
UNION 
SELECT 20
UNION 
SELECT 40
UNION
SELECT 40000
UNION
SELECT 50000
UNION 
SELECT 60000

;WITH Smalls AS (
SELECT COUNT(val) Small FROM @tst WHERE val < 100 
), Bigs AS(
select count(val) Big from @tst where val >= 100
)
SELECT Small, Big
 FROM Smalls, Bigs
于 2012-09-18T05:15:02.893 回答
0
create table datatable
(
  data int
)

insert into datatable values(10) 

insert into datatable values(15)

insert into datatable values(20)

insert into datatable values(40)

insert into datatable values(40000)

insert into datatable values(50000)

insert into datatable values(60000)



create table outputtable 
( 
  small int , 
  big int 
)

insert into outputtable 
(
  small,
  big
)

select (select count(data) from datatable where data<100),
       (select count(data) from datatable where data>=100)

select * from datatable

select * from outputtable
于 2012-09-18T09:38:52.387 回答