0

我有这样的数据,

KOD    Voucher
1        10
2         2
3        11
4         5
5        23
6         1
7        23

我只想要结果是这样的

< 10 = 3
> 10 = 4

如何在sql中做到这一点?

4

4 回答 4

3

尝试这个:

SELECT
  SUM(CASE WHEN voucher < 10 THEN 1 ELSE 0 END) AS "< 10",
  SUM(CASE WHEN voucher > 10 THEN 1 ELSE 0 END) AS "> 10"
FROM table;

SQL 小提琴演示

但这只会为您提供 3 个> 10

< 10  > 10
3       3

您必须使用谓词>=来获取> 10自 10 not > 10nor以来的 4 个值< 10

更新的 SQL Fiddle 演示

于 2012-11-29T10:52:16.353 回答
1
SELECT COUNT(1) AS "< 10"
FROM myTable
WHERE Voucher < 10 

SELECT COUNT(1) AS ">= 10"
FROM myTable
WHERE Voucher >= 10 
于 2012-11-29T10:53:11.260 回答
0

以行形式

  select case when voucher<10 then '< 10' else '>= 10' end breakdown,
         count(1) total
    from tbl
group by case when voucher<10 then '< 10' else '>= 10' end;

结果:

 breakdown | total
 < 10      | 3
 >= 10     | 4

以列形式

  select count(case when voucher<10 then 1 end) [< 10],
         count(case when voucher>=10 then 1 end) [>= 10]
    from tbl;

结果:

 < 10  | >= 10
 3     | 4
于 2012-11-29T10:53:31.413 回答
0
select '< 10 = '+cast(count(KOD) as Varchar(100)) from t where Voucher<10
union
select '> 10 = '+cast(count(KOD) as Varchar(100)) from t where Voucher>=10

SQLFiddle 示例

于 2012-11-29T11:46:07.640 回答