【问题标题】:Cross table creation with subqueries使用子查询创建交叉表
【发布时间】:2018-10-02 06:21:40
【问题描述】:

我需要制作一个表格,根据汽车的状态(旧的或新的)以及损坏情况(损坏与否)来显示已售出的汽车数量。请记住,每辆汽车可以有多个 DamageID,而许多汽车也可以有相同的 DamageID(我只需要计算损坏的汽车)。我需要打印一张表格,该表格将在 X 轴上显示状态(新和已使用),然后在 Y 轴上我需要汽车的损坏情况(无论损坏类型和每辆车的 DamageID 数量如何,损坏与否)。我尝试使用数据透视表技术,但我无法弄清楚。欢迎大家提出意见。

Select 
(select Count(CD.CarDamageID)
From CarDamage as CD
inner join Invoice as I on I.CarInventoryID = CD.CarInventoryID
) as Damage
,
(select Count(I.InvoiceID)
From Invoice I
inner join CarInventory CI on CI.CarInventoryID = I.CarInventoryID
Inner join CarState CS on CS.CarStateID = CI.CarStateID
Where CS.[State] ='New') as NEW
,
(select Count (I.InvoiceID)
From Invoice I
inner join CarInventory CI on CI.CarInventoryID = I.CarInventoryID
Inner join CarState CS on CS. CarStateID = CI.CarStateID
Where CS.[State]='Used') as USED

这就是我现在所拥有的。

【问题讨论】:

  • 不是一个很好的“问”问题埃米尔。阅读有关如何提问的 SO 说明。这是一个密集的文本块!正在使用任何特定的 SQL 产品吗?

标签: pivot crosstab


【解决方案1】:

对于大多数 SQL 产品,您可以使用来自公用表表达式 (CTE) 的普通“分组依据”。例如

with damagecounts as (
  select
    cs.state as carstate
    ,i.carinventoryid
    ,cd.cardamageid
    ,case when cs.state = 'New' then 1 end as newdamage
    ,case when cs.state = 'Used' then 1 end as useddamage
  from cardamage as cd
  inner join invoice as i on i.carinventoryid = cd.carinventoryid
  inner join carinventory as ci on ci.carinventoryid = i.carinventoryid
  inner join carstate as cs on cs.carstateid = ci.carstateid
  where cs.state in ('New', 'Used')
)
select
  carstate
  ,carinventoryid
  ,count(newdamage) as newdamage
  ,count(useddamage) as useddamage
from damagecounts
group by carstate, carinventoryid
order by carstate, carinventoryid

使用 Postgres 等,您可以获得更简单的过滤器

select
  cs.state as carstate
  ,i.carinventoryid
  ,count(cd.cardamageid) filter (where cs.state = 'New') as newdamage
  ,count(cd.cardamageid) filter (where cs.state = 'Used') as useddamage
from cardamage as cd
inner join invoice as i on i.carinventoryid = cd.carinventoryid
inner join carinventory as ci on ci.carinventoryid = i.carinventoryid
inner join carstate as cs on cs.carstateid = ci.carstateid
where cs.state in ('New', 'Used')
group by carstate, carinventoryid
order by carstate, carinventoryid

使用 Microsoft SQL Server,您可以使用 PIVOT 语句,但这与基本的标准 SQL 相去甚远

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-11
    • 1970-01-01
    • 2020-11-10
    • 1970-01-01
    • 2019-05-25
    • 2013-07-05
    相关资源
    最近更新 更多