我有一个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
怎么做?有可能吗?
答案 0 :(得分: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
答案 1 :(得分:10)
尝试子查询而不是UNION ALL
,如下所示:
SELECT
(SELECT COUNT(data) FROM tableA WHERE data < 100) AS Small,
(SELECT COUNT(data) FROM tableA WHERE data >= 100) AS Big
答案 2 :(得分: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
答案 3 :(得分: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