我正在尝试编写一个SQL查询,该查询将显示包含应用程序" iMobilePOS"的任何设备的商店,ID,MAC和AppName。和" StoreFulfill"在AppName列中。我非常接近......我想要做的是每个设备只显示两行。一个包含" iMobile" AppName值,另一个包含" StoreFill" AppName值。目前,结果显示设备已安装的每个应用程序的一行...这是我的查询参考:
SELECT DISTINCT storenumber,
registerid,
wifi_mac,
appname
FROM mpos_health.dbo.mdat_data_report AS mdat
INNER JOIN mpos_health.dbo.mpos_health_report AS mpos
ON mdat.wifi_mac = mpos.wifimac
WHERE EXISTS (SELECT *
FROM mpos_health.dbo.mpos_health_report AS mpos
WHERE mpos.wifimac = mdat.wifi_mac
AND appname = 'iMobilePOS')
AND EXISTS (SELECT *
FROM mpos_health.dbo.mpos_health_report AS mpos
WHERE mpos.wifimac = mdat.wifi_mac
AND appname = 'StoreFulfill');
我正在加入这两个表,因为它们都包含我想要包含的信息,它们的共同价值是设备的WiFiMAC。此查询以我想要的方式过滤设备,但它包括所有应用程序。例如,以下是我目前看到的内容:
在哪里,我不想看到MobileIron的第二行,我只想看到其他两行。包含iMobilePOS和StoreFulfill。
非常感谢任何建议。非常感谢你。
答案 0 :(得分:0)
SELECT DISTINCT storenumber,
registerid,
wifi_mac,
appname
FROM mpos_health.dbo.mdat_data_report AS mdat
INNER JOIN mpos_health.dbo.mpos_health_report AS mpos
ON mdat.wifi_mac = mpos.wifimac
WHERE EXISTS (SELECT *
FROM mpos_health.dbo.mpos_health_report AS mpos
WHERE mpos.wifimac = mdat.wifi_mac
AND appname = 'iMobilePOS')
AND EXISTS (SELECT *
FROM mpos_health.dbo.mpos_health_report AS mpos
WHERE mpos.wifimac = mdat.wifi_mac
AND appname = 'StoreFulfill')
AND Appname IN ('iMobilePOS, 'StoreFulfill')
答案 1 :(得分:0)
您也可以使用 common table expression row_number() 来执行此操作:
with cte as (
select distinct
storenumber
, registerid
, wifi_mac
, appname
, rn = row_number() over (partition by wifi_mac order by AppName)
from mpos_health.dbo.mdat_data_report as mdat
inner join mpos_health.dbo.mpos_health_report as mpos
on mdat.wifi_mac = mpos.wifimac
and Appname in ('iMobilepos','StoreFulfill')
)
select
storenumber
, registerid
, wifi_mac
, appname
, rn
from cte o
where exists (
select 1
from cte as i
where i.wifi_mac =o.wifimac
and i.rn>1
)
或使用union
:
select distinct
storenumber
, registerid
, wifi_mac
, appname
from mpos_health.dbo.mdat_data_report as mdat
inner join mpos_health.dbo.mpos_health_report as mpos
on mdat.wifi_mac = mpos.wifimac
and Appname = 'iMobilepos'
where exists (
select 1
from mpos_health.dbo.mpos_health_report as mpos
where mpos.wifimac = mdat.wifi_mac
and appname = 'StoreFulfill'
)
union all
select distinct
storenumber
, registerid
, wifi_mac
, appname
from mpos_health.dbo.mdat_data_report as mdat
inner join mpos_health.dbo.mpos_health_report as mpos
on mdat.wifi_mac = mpos.wifimac
and Appname = 'StoreFulfill'
where exists (
select 1
from mpos_health.dbo.mpos_health_report as mpos
where mpos.wifimac = mdat.wifi_mac
and appname = 'iMobilepos'
)