使用子查询

时间:2018-04-21 21:00:55

标签: pivot crosstab

我需要制作一张桌子,根据汽车状态(使用过的或新的)以及损坏情况(损坏与否)显示已售出多少辆汽车。请记住,每辆车都有很多DamageID,而且很多车都有相同的DamageID(我只需要计算已损坏的车辆)。我需要打印一张表格,在X轴上显示状态(NEW和USED),然后在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

这就是我现在所拥有的。

1 个答案:

答案 0 :(得分:0)

对于大多数SQL产品,您可以使用公共表表达式(CTE)中的普通“group by”。 e.g。

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