简体   繁体   English

SQL:Select 满足条件的不同项目

[英]SQL: Select distinct items where condition is met

I have a relation in a database as follows:我在数据库中有如下关系:

constituents                                                         Symbol
[{"weight":0.5, "ticker":"WPM"},{"weight":0.5, "ticker":"AEM"}]      GLD
[{"weight":0.5, "ticker":"XYZ"},{"weight":0.5, "ticker":"ABC"}]      KLE
[{"weight":1.0, "ticker":"TSLA"}]                                    TSLA
[{"weight":1.0, "ticker":"MSFT"}]                                    MSFT
[{"weight":0.4, "ticker":"XYZ"},{"weight":0.6, "ticker":"ABC"}]      KLE
[{"weight":0.3, "ticker":"BBBY"},{"weight":0.7, "ticker":"GME"}]     MEME

I want to get the distinct symbols where the constituents column contains more than 1 json in the list.我想获得不同的符号,其中成分列在列表中包含超过 1 个 json。 So the outcome should be所以结果应该是

GLD, KLE, MEME

My attempt is:我的尝试是:

SELECT DISTINCT "Symbol" FROM "MyTable" WHERE JSONB_ARRAY_LENGTH("constitutents")>1

but I get an error: ERROR: cannot get array length of a non-array但我收到一个错误: ERROR: cannot get array length of a non-array

Just check if it has a comma in it:只需检查它是否有逗号:

SELECT DISTINCT "Symbol" 
FROM "MyTable"
WHERE CONTAINS("constitutents",',')

It depemds how our column is defined as JSON or JSONB, so you need to use the appropriate functions它取决于我们的列如何定义为 JSON 或 JSONB,因此您需要使用适当的函数

JSONB JSONB

CREATE TABLE T2
    ("constituents" JSONB, "Symbol" varchar(4))
;
    
INSERT INTO T2
    ("constituents", "Symbol")
VALUES
    ('[{"weight":0.5, "ticker":"WPM"},{"weight":0.5, "ticker":"AEM"}]', 'GLD'),
    ('[{"weight":0.5, "ticker":"XYZ"},{"weight":0.5, "ticker":"ABC"}]', 'KLE'),
    ('[{"weight":1.0, "ticker":"TSLA"}]', 'TSLA'),
    ('[{"weight":1.0, "ticker":"MSFT"}]', 'MSFT'),
    ('[{"weight":0.4, "ticker":"XYZ"},{"weight":0.6, "ticker":"ABC"}]', 'KLE'),
    ('[{"weight":0.3, "ticker":"BBBY"},{"weight":0.7, "ticker":"GME"}]', 'MEME')
;

 CREATE TABLE
 INSERT 0 6
SELECT "Symbol" FROM T2 WHERE JSONB_ARRAY_LENGTH("constituents") > 1
Symbol象征
GLD GLD
KLE KLE
KLE KLE
MEME模因
SELECT 4

fiddle小提琴

Json Json

CREATE TABLE T2
    ("constituents" JSON, "Symbol" varchar(4))
;
    
INSERT INTO T2
    ("constituents", "Symbol")
VALUES
    ('[{"weight":0.5, "ticker":"WPM"},{"weight":0.5, "ticker":"AEM"}]', 'GLD'),
    ('[{"weight":0.5, "ticker":"XYZ"},{"weight":0.5, "ticker":"ABC"}]', 'KLE'),
    ('[{"weight":1.0, "ticker":"TSLA"}]', 'TSLA'),
    ('[{"weight":1.0, "ticker":"MSFT"}]', 'MSFT'),
    ('[{"weight":0.4, "ticker":"XYZ"},{"weight":0.6, "ticker":"ABC"}]', 'KLE'),
    ('[{"weight":0.3, "ticker":"BBBY"},{"weight":0.7, "ticker":"GME"}]', 'MEME')
;

 CREATE TABLE
 INSERT 0 6
SELECT "Symbol" FROM T2 WHERE JSON_ARRAY_LENGTH("constituents") > 1
Symbol象征
GLD GLD
KLE KLE
KLE KLE
MEME模因
SELECT 4

fiddle小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM