【问题标题】:two counts in the same row同一行中的两个计数
【发布时间】:2018-02-24 21:58:31
【问题描述】:

无法在同一行中设置 2 个计数。 我的查询结果是这样的: enter image description here

我希望最终结果看起来像这样: enter image description here 最后将当前的 count1 构建到 count2

我对案例的尝试不成功:SELECT Date,Shift, CASE description WHEN 'Defects' THEN count ELSE 0 END AS Defect_Count , CASE description WHEN 'Total' THEN count ELSE 0 END AS Total_Count FROM ("Queries union)

【问题讨论】:

  • 您使用的是什么数据库管理系统? Oracle、mysql 还是 mssql?
  • 我正在使用 mssql (2012)

标签: count pivot row pvts


【解决方案1】:

给你。希望这可以帮助。谢谢。

MYSQL:
select
    t.dates, t.shift,
    sum(case when t.description = 'Defects' then t.counts else 0 end) as `Defects`,
    sum(case when t.description = 'Total' then t.counts else 0 end) as `Total`
from (
    select *
    from tbl ) t
group by t.dates, t.shift
order by t.dates, t.shift

ORACLE:
SELECT dates, shift, defects , total
FROM
(
  SELECT *
  FROM tbl
)  
PIVOT
(
  sum(counts)
  FOR description IN ('Defects' as defects, 'Total' as total)
)  
ORDER BY dates

Result:
dates       shift Defects  Total
2018-01-20  AM      21     56
2018-01-20  PM      19     54
2018-01-23  AM      16     58
2018-01-23  PM      20     45

【讨论】:

    【解决方案2】:

    非常感谢正在为第一步工作(计入同一行)。

    我现在将尝试建立百分比(缺陷总数)。 谢谢。

    建立百分比(缺陷总数): select dates,shift,defects,total,round((100*defects/total),2) Percent2Total from(select t.dates, t.shift, sum(case when t.description = 'Defects' then t.counts else 0 end) as 'Defects', sum(case when t.description = 'total' then t.counts else 0 end) as 'Total' from ( select * from tbl ) t group by t.dates, t.shift )q order by dates,Shift。 是否可以仅使用 Pivot 构建它?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-19
      • 2022-01-23
      • 2016-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多