嗨我有一个复杂的(我的SQL标准)计数,我需要在多个表上执行,我很乐意帮助。
我有三张桌子:
RELEASE
ID |METADATA_ID|Is_Active|Creation_Source|Release_Status
123456|123 | Y | A1 |Active
134567|124 | Y | A1 |Active
145678|125 | N | A2 |Closed
RELEASE_METADATA
ID |UPC
123 |8001
124 |8002
125 |8003
RELEASE_COUNTRY_RIGHT
(RELEASE)ID |COUNTRY_ID|MARKETING_RIGHT|OPT_OUT
123456 | UK | N |N
123456 | US | Y |N
123456 | FR | Y |Y
134567 | UK | Y |N
134567 | US | Y |Y
145678 | UK | Y |Y
145678 | FR | Y |N
我需要能够通过RELEASE的Source和Status过滤结果,包括来自RELEASE_METADATA的UPC,并计算RELEASE_COUNTRY_RIGHT中相关的行数,Marketing和Selected字段。
所以我的结果会是这样的:
ID |Is_Active|Creation_Source|Release_Status|UPC |RELEASE_COUNTRY_RIGHT Rows|MARKETING_RIGHT|OPT_OUT
123456| Y | A1 |Active |8001| 3 | 2 | 1
134567| Y | A1 |Active |8002| 2 | 2 | 1
非常感谢任何帮助。
干杯!
更新: 我尝试过使用下面的SHALAKA解决方案,但是在替换下表所示的表和字段名称之后我遇到了麻烦。我已经更新了上面的表格和字段名称,因为我意识到我所拥有的可能会产生误导。 还有一个额外的字段,我错过了,因为连接不像我预期的那样。 RELEASE通过release.ID = release_metadata_id与RELEASE_METADATA连接,第三个表需要通过release.ID = release_country_right.release_ID加入。
这是我的尝试:
SELECT grp_1.*, COUNT(a5.OPT_OUT) OPT_OUT
FROM (SELECT grp.*, COUNT(a4.MARKETING_RIGHT) MARKETING_RIGHT
FROM (SELECT a1.id,
a1.IS_ACTIVE,
a1.CREATION_SOURCE,
a1.RELEASE_STATUS,
a2.upc,
COUNT(a3.RELEASE_ID) a_row
FROM dschd.release a1, dschd.release_metadata a2, DSCHD.RELEASE_COUNTRY_RIGHT a3
WHERE a1.RELEASE_METADATA_ID = a2.id
AND a1.id = a3.RELEASE_ID
AND a1.IS_ACTIVE = 'Y'
GROUP BY a1.id, a1.IS_ACTIVE, a1.CREATION_SOURCE, a1.RELEASE_STATUS, a2.UPC) grp,
DSCHD.RELEASE_COUNTRY_RIGHT a4
WHERE a4.OPT_OUT = grp.id
AND a4.MARKETING_RIGHT = 'N'
GROUP BY grp.id,
grp.IS_ACTIVE,
grp.CREATION_SOURCE,
grp.RELEASE_STATUS,
grp.upc,
grp.a_row) grp_1,
DSCHD.RELEASE_COUNTRY_RIGHT a5
WHERE a5.RELEASE_ID = grp_1.id
AND a5.OPT_OUT = 'Y'
GROUP BY grp_1.id,
grp_1.IS_ACTIVE,
grp_1.CREATION_SOURCE,
grp_1.RELEASE_STATUS,
grp_1.upc,
grp_1.a_row,
grp_1.MARKETING_RIGHT
答案 0 :(得分:0)
SELECT grp_1.*, COUNT(a5.selected) selected
FROM (SELECT grp.*, COUNT(a4.marketing) marketing
FROM (SELECT a1.id,
a1.active,
a1.source,
a1.status,
a2.ref,
COUNT(a3.id) a_row
FROM data1 a1, data2 a2, data3 a3
WHERE a1.id = a2.id
AND a2.id = a3.id
AND a1.active = 'Y'
GROUP BY a1.id, a1.active, a1.source, a1.status, a2.ref) grp,
data3 a4
WHERE a4.id = grp.id
AND a4.marketing = 'Y'
GROUP BY grp.id,
grp.active,
grp.source,
grp.status,
grp.ref,
grp.a_row) grp_1,
data3 a5
WHERE a5.id = grp_1.id
AND a5.selected = 'Y'
GROUP BY grp_1.id,
grp_1.active,
grp_1.source,
grp_1.status,
grp_1.ref,
grp_1.a_row,
grp_1.marketing