【问题标题】:Count the difference in SQL result统计 SQL 结果的差异
【发布时间】:2016-01-08 02:14:52
【问题描述】:

我有一张这样的桌子。

+-------------+-------+
|    vtype    | isreq |
+-------------+-------+
| Near        |     0 |
| Near        |     1 |
| Far         |     0 |
| Near to far |     0 |
+-------------+-------+

我想获得具有不同isreq 但类型相同的号码。请问有人吗?

【问题讨论】:

  • 你的意思是你只需要满足你条件的计数?
  • 如果类型相同且isreq不同,则计数为1。
  • 对于给定的示例,显示您的预期输出。
  • 这是我的查询 Select count(*) from @table where type = type and isreq != isreq 我的预期结果是 1
  • 如果两个vtype的isreq相同,那么count应该是0怎么办?

标签: sql linq linq-to-sql


【解决方案1】:

这将满足您的要求。尝试使用更多数据进行测试。

select count(*) from
    yourTable a 
        inner join 
    yourTable b
on a.vtype=b.vtype
and a.isreq < b.isreq
group by a.vtype,a.isreq

在 MySQL 上查看小提琴演示

http://sqlfiddle.com/#!9/b51bf8/11

【讨论】:

  • 如果它适合您,请点击答案左侧的tick 符号接受答案,以便将其关闭。
【解决方案2】:

我得到了我需要的东西。

DECLARE @table as table(vtype varchar(15),isreq varchar(5))

insert into @table values ('Near','0')
insert into @table values ('Near','1')
insert into @table values ('Far','0')
insert into @table values ('Near to Far','0')

SELECT count(*) FROM @table WHERE vtype = vtype and isreq = isreq 
SELECT DISTINCT(COUNT(*)-1) AS result FROM @table WHERE vtype = vtype and isreq = isreq GROUP BY vtype HAVING (COUNT(*)-1)>0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-13
    • 2015-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多