帮助使用 case 和 group 进行 sql 查询

发布于 2024-11-03 09:18:50 字数 304 浏览 2 评论 0原文

我有一个带有日期和一个名为 posneg 的字段的数据库表,该值是“pos”、“neu”或“neg”。

我需要一个结果集,其中添加 posneg 值,然后按日期分组。就像这样

2010-10-03    5   (on that date it could be 12 pos, 5 neu and 7 neg)
2010-10-04    -3  (on that date maybe 10 pos, 2 neu and 13 neg)
...and so on

基本上,neu 并不重要,正如你所看到的。

I have a DB Table with a date and a field called posneg, the value is either 'pos', 'neu' or 'neg'.

I need a result set where the posneg values are added and then grouped by date. Like this

2010-10-03    5   (on that date it could be 12 pos, 5 neu and 7 neg)
2010-10-04    -3  (on that date maybe 10 pos, 2 neu and 13 neg)
...and so on

Basically the neu doesn't matter, as you see.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

瀞厅☆埖开 2024-11-10 09:18:50
SELECT
  date,
  posneg = SUM(
    CASE posneg
      WHEN 'pos' THEN 1
      WHEN 'neg' THEN -1
      ELSE 0
    END
  )
FROM atable
GROUP BY date
SELECT
  date,
  posneg = SUM(
    CASE posneg
      WHEN 'pos' THEN 1
      WHEN 'neg' THEN -1
      ELSE 0
    END
  )
FROM atable
GROUP BY date
萌︼了一个春 2024-11-10 09:18:50

试试这个:

SELECT date, SUM(IF(posneg='pos',1,IF(posneg='neg',-1,0))) as total
FROM table GROUP BY date

Try this:

SELECT date, SUM(IF(posneg='pos',1,IF(posneg='neg',-1,0))) as total
FROM table GROUP BY date
把时间冻结 2024-11-10 09:18:50
with tab as(

select cast('12/12/2010' as smalldatetime) as dt, 'neg' as posneg 
union all
select cast('12/12/2010' as smalldatetime) as dt, 'pos' as posneg 
union all
select cast('12/12/2010' as smalldatetime) as dt, 'pos' as posneg 
union all
select cast('12/12/2010' as smalldatetime) as dt, 'pos' as posneg 
union all
select cast('12/15/2010' as smalldatetime) as dt, 'neg' as posneg 
union all
select cast('12/15/2010' as smalldatetime) as dt, 'neg' as posneg 
union all
select cast('12/15/2010' as smalldatetime) as dt, 'pos' as posneg
)

select dt,
sum(case when posneg='pos' then 1
         when posneg='neg' then -1
         else 0 end) as total
         from tab
         group by dt
with tab as(

select cast('12/12/2010' as smalldatetime) as dt, 'neg' as posneg 
union all
select cast('12/12/2010' as smalldatetime) as dt, 'pos' as posneg 
union all
select cast('12/12/2010' as smalldatetime) as dt, 'pos' as posneg 
union all
select cast('12/12/2010' as smalldatetime) as dt, 'pos' as posneg 
union all
select cast('12/15/2010' as smalldatetime) as dt, 'neg' as posneg 
union all
select cast('12/15/2010' as smalldatetime) as dt, 'neg' as posneg 
union all
select cast('12/15/2010' as smalldatetime) as dt, 'pos' as posneg
)

select dt,
sum(case when posneg='pos' then 1
         when posneg='neg' then -1
         else 0 end) as total
         from tab
         group by dt
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文