有没有更优雅的方式做这种事情?我有一个仪表板,我正在尝试填充信息,我只需要一些计数。如果可能的话,我想在一个查询中完成所有操作,但下面的查询似乎很愚蠢。任何建议将不胜感激。
select
UserCount = (
select count(*) from net_ou
inner join art_asset on net_ou.net_ouid = art_asset.net_ouid
inner join idb_interface on idb_interface.art_asset_id = art_asset.art_asset_id
inner join nsd_interfacecode on nsd_interfacecode.nsd_interfacecodeid = idb_interface.nsd_interfacecodeid
inner join nsd_interfacetype on nsd_interfacetype.nsd_interfacetypeid = idb_interface.nsd_interfacetypeid
where net_ou.displayname = 'abcd' and nsd_interfacecode.code = 1 and nsd_interfacetype.physical = 1),
PrinterCount = (
select count(*) as PrinterCount from net_ou
inner join art_asset on net_ou.net_ouid = art_asset.net_ouid
inner join idb_interface on idb_interface.art_asset_id = art_asset.art_asset_id
inner join nsd_interfacecode on nsd_interfacecode.nsd_interfacecodeid = idb_interface.nsd_interfacecodeid
inner join nsd_interfacetype on nsd_interfacetype.nsd_interfacetypeid = idb_interface.nsd_interfacetypeid
where net_ou.displayname = 'abcd' and nsd_interfacecode.code = 2 and nsd_interfacetype.physical = 1),
TrunkCount = (
select count(*) as TrunkCount from net_ou
inner join art_asset on net_ou.net_ouid = art_asset.net_ouid
inner join idb_interface on idb_interface.art_asset_id = art_asset.art_asset_id
inner join nsd_interfacecode on nsd_interfacecode.nsd_interfacecodeid = idb_interface.nsd_interfacecodeid
inner join nsd_interfacetype on nsd_interfacetype.nsd_interfacetypeid = idb_interface.nsd_interfacetypeid
where net_ou.displayname = 'abcd' and nsd_interfacecode.code = 4 and nsd_interfacetype.physical = 1)
答案 0 :(得分:4)
您可以使用CASE
:
select
SUM(CASE WHEN nsd.interfacecode.code = 1 THEN 1 ELSE 0 END) as UserCount,
SUM(CASE WHEN nsd.interfacecode.code = 2 THEN 1 ELSE 0 END) as PrinterCount,
SUM(CASE WHEN nsd.interfacecode.code = 4 THEN 1 ELSE 0 END) as TrunkCount
from net_ou
inner join art_asset on net_ou.net_ouid = art_asset.net_ouid
inner join idb_interface on idb_interface.art_asset_id = art_asset.art_asset_id
inner join nsd_interfacecode on nsd_interfacecode.nsd_interfacecodeid = idb_interface.nsd_interfacecodeid
inner join nsd_interfacetype on nsd_interfacetype.nsd_interfacetypeid = idb_interface.nsd_interfacetypeid
where net_ou.displayname = 'abcd'
and nsd_interfacetype.physical = 1
答案 1 :(得分:1)
select nsd_interfacecode.code, count(*) from net_ou
inner join art_asset on net_ou.net_ouid = art_asset.net_ouid
inner join idb_interface on idb_interface.art_asset_id = art_asset.art_asset_id
inner join nsd_interfacecode on nsd_interfacecode.nsd_interfacecodeid = idb_interface.nsd_interfacecodeid
inner join nsd_interfacetype on nsd_interfacetype.nsd_interfacetypeid = idb_interface.nsd_interfacetypeid
where net_ou.displayname = 'abcd' and and nsd_interfacetype.physical = 1
group by nsd_interfacecode.code
这应该给你你的价值观,假设我没有错过任何不同的查询。