Пытался сделать через ROW_NUMBERS() OVER (PATRITION BY date ORDER BY date, time, check), ну тут, конечно, получается он игнорит check и просто проставляет 1,2,3,4,5.
Если добавить PATRITION BY date, check, то он, блин, сортирует по check потом и тоже не то выходит
SELECT json_build_object(
'account_id', id,
'first_name', first_name,
'last_name', last_name
) AS author
FROM accounts
json_build_object(
'post_id', p.id,
'body', p.body,
'author', json_build_object(
'account_id', a.id,
'first_name', a.first_name,
'last_name', a.last_name
)
)
при объединении таблиц posts и accountsSELECT json_agg(json_build_object(
'post_id', p.id,
'body', p.body,
'author', json_build_object(
'account_id', a.id,
'first_name', a.first_name,
'last_name', a.last_name
)
)) AS posts
FROM posts p
JOIN accounts a ON a.id = p.author_id
SELECT json_agg(json_build_object(
'comment_id', c.id,
'body', c.body,
'author', json_build_object(
'account_id', a.id,
'first_name', a.first_name,
'last_name', a.last_name
)
)) AS comments
FROM comments c
JOIN accounts a ON a.id = c.author_id
GROUP BY post_id
WITH cmts AS (
SELECT json_agg(json_build_object(
'comment_id', c.id,
'body', c.body,
'author', json_build_object(
'account_id', a.id,
'first_name', a.first_name,
'last_name', a.last_name
)
)) AS comments,
post_id
FROM comments c
JOIN accounts a ON a.id = c.author_id
GROUP BY post_id
)
SELECT json_agg(json_build_object(
'post_id', p.id,
'body', p.body,
'author', json_build_object(
'account_id', a.id,
'first_name', a.first_name,
'last_name', a.last_name
),
'comments', COALESCE(c.comments, '[]')
)) AS "posts with comments"
FROM posts p
JOIN accounts a ON a.id = p.author_id
LEFT JOIN cmts c ON c.post_id = p.id
WITH f AS (
SELECT 'PARAM1 PARAM3 PARAM7' as findstr
),
fr AS (
SELECT t.value AS param
FROM f
CROSS APPLY STRING_SPLIT(f.findstr, ' ') t
)
SELECT d.id, count(1) AS num_matches
FROM data d
CROSS JOIN fr
WHERE charindex(fr.param, d.parameters) > 0
GROUP BY id
HAVING count(1) >= 2
;
WITH f AS (
SELECT 'PARAM1 PARAM3 PARAM7' as findstr
)
SELECT d.id, count(1) AS num_matches
FROM data d
CROSS APPLY STRING_SPLIT(d.parameters, ' ') ds
JOIN f ON 1=1
WHERE charindex(ds.value, f.findstr) > 0
GROUP BY d.id
HAVING count(1) >= 2
;
sqlite3.exe my_example_db.sqlt
create table ru_word (word varchar(100), freq INT);
.separator " "
.import ru_50k.txt ru_word
: переходим в папку с БД, там же должен быть файлru_50k.txt
cd C:\tmp
: открываем БД в sqlite3
c:\bin\sqlite3.exe my_example_db.sqlt
SQLite version 3.41.0 2023-02-21 18:09:37
Enter ".help" for usage hints.
sqlite> create table ru_word (word varchar(100), freq INT);
sqlite> .tables
ru_word
sqlite> .separator " "
sqlite> .import ru_50k.txt ru_word
sqlite> SELECT count(*) FROM ru_word;
50000
sqlite> SELECT MAX(freq) FROM ru_word;
3854593
sqlite> SELECT * FROM ru_word LIMIT 10;
я 3854593
не 3244771
что 2665565
в 2212420
и 2179689
ты 2067418
это 1999607
на 1240437
с 1128276
он 966203
sqlite> .quit
столбец1 столбец2 результат
фф 123 1
фф 456 0
йцу 123 0
-- количество дублирующихся записей
SELECT столбец1, столбец2, count(*)
FROM таблица
GROUP BY столбец1, столбец2;
-- количество ПАР!!
SELECT столбец1, столбец2, count(*) div 2
FROM таблица
GROUP BY столбец1, столбец2;
-- если необходимо именно как в вопросе (количество дублирующихся записей):
SELECT t1.столбец1, t1.столбец2, cnt AS результат
FROM таблица t1
JOIN (
SELECT столбец1, столбец2, count(*) cnt
FROM таблица
GROUP BY столбец1, столбец2) t2 ON t2.столбец1 = t1.столбец1
AND t2.столбец2 = t1.столбец2
;
-- если необходимо именно как в вопросе (КОЛИЧЕСТВО ПАР!!):
SELECT t1.столбец1, t1.столбец2, cnt div 2 AS результат
FROM таблица t1
JOIN (
SELECT столбец1, столбец2, count(*) cnt
FROM таблица
GROUP BY столбец1, столбец2) t2 ON t2.столбец1 = t1.столбец1
AND t2.столбец2 = t1.столбец2
;
\u0442\u0435\u043a\u0441\u0442\u0020\u0432\u0020\u044e\u043d\u0438\u043a\u043e\u0434
import re
regex = r"(\\u[0-9a-zA-Z]{4})(?!\\u[0-9a-zA-Z]{4}).*?(\\u[0-9a-zA-Z]{4})"
test_str = ("\\u0442\\u0435\\u043a\\u0441\\u0442\\u0020\\u0432\\u0020\\u044e\\u043d\\u0438\\u043a\\u043e\\u0434\n\n"
"\\u0442\\u0435dsds\\n\\u043a\\u0441\\u0442das\\u0020\\u0432dsdddddd\\u0020\\u044e\\u043d\\n\\n\\n\\u0438\\u043a\\u043e\\u0434")
subst = "\\1\\2"
# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0)
if result:
print (result)
SELECT count(DISTINCT c.user_id) AS first_day_order
FROM clients c
INNER JOIN orders o ON c.user_id = o.user_id
WHERE DATE(c.registered_datetime) = DATE(o.when_start)
AND DATE(c.registered_datetime) BETWEEN '2021-09-01' AND '2021-09-30'
;
SELECT count(c.user_id) AS first_day_order
FROM clients c
WHERE DATE(c.registered_datetime) BETWEEN '2021-09-01' AND '2021-09-30'
AND EXISTS (
SELECT 1 FROM orders o
WHERE c.user_id = o.user_id
AND DATE(c.registered_datetime) = DATE(o.when_start)
)
;
sql_script = """
CREATE TABLE IF NOT EXISTS information
(id INTEGER PRIMARY KEY AUTOINCREMENT,userid INTEGER,money INTEGER,weight INTEGER,sportmode INTEGER);
CREATE TABLE IF NOT EXISTS task
(id INTEGER PRIMARY KEY AUTOINCREMENT,list TEXT, status INTEGER);
CREATE TABLE IF NOT EXISTS what
(mycommands TEXT);
CREATE TABLE IF NOT EXISTS accounts
(login TEXT, password TEXT, token TEXT)
"""
for sql in sql_script.split(";\n"):
cursor.execute(sql)
select cal.cal_date, count(person)
from some_table st
right join (
-- генерируем календарь - набор дат
select *
from (
select adddate('1970-01-01',t4*10000 + t3*1000 + t2*100 + t1*10 + t0) cal_date
from
(select 0 t0 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
(select 0 t1 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
(select 0 t2 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
(select 0 t3 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
(select 0 t4 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4
) v
where cal_date between '2021-11-01' and '2021-11-30'
) cal on cal.cal_date = st.date_field
group by cal.cal_date
SELECT '2021-11-01' + INTERVAL seq DAY FROM seq_0_to_29;
select cal.cal_date, count(person)
from some_table st
right join (
-- генерируем календарь - набор дат
SELECT '2021-11-01' + INTERVAL seq DAY as cal_date FROM seq_0_to_29
) cal on cal.cal_date = st.date_field
group by cal.cal_date
;
alter session set events '22829 trace name context forever';
alter session set events '22829 trace name context forever';
WITH
test AS (
SELECT 'проул.' as code, 'проул.|пр-к|' as str FROM dual UNION
SELECT 'ул.' as code, 'ул.|улица|ул-ца|' as str FROM dual UNION
SELECT 'пер.' as code, 'пер.|переулок|' as str FROM dual UNION
SELECT 'кв-л' as code, 'кв-л|квартал|' as str FROM dual UNION
SELECT 'линия' as code, 'линия|' as str FROM dual UNION
SELECT 'парк' as code, 'парк|' as str FROM dual UNION
SELECT 'рзд' as code, 'рзд|разъезд|' as str FROM dual UNION
SELECT 'сад' as code, 'Сад|' as str FROM dual UNION
SELECT 'тракт' as code, 'тракт|' as str FROM dual UNION
SELECT 'тер' as code, 'тер|территория|' as str FROM dual UNION
SELECT 'ст' as code, 'ст|станция|' as str FROM dual UNION
SELECT 'сл' as code, 'сл|слобода|' as str FROM dual UNION
SELECT 'пр-кт' as code, 'пр.|проспект|пр-кт|' as str FROM dual UNION
SELECT 'шоссе' as code, 'ш.|шоссе|' as str FROM dual UNION
SELECT 'пл' as code, 'пл|площадь|пл-дь|' as str FROM dual UNION
SELECT 'наб.' as code, 'наб.|набережная|наб-ая|' as str FROM dual UNION
SELECT 'тупик' as code, 'тупик|' as str FROM dual UNION
SELECT 'мост' as code, 'мост|' as str FROM dual UNION
SELECT 'пр.' as code, 'проезд|пр.|' as str FROM dual UNION
SELECT 'блв.' as code, 'блв.|бульвар|' as str FROM dual UNION
SELECT 'мкн.' as code, 'мкн.|микрорайон|' as str FROM dual UNION
SELECT 'пос.' as code, 'пос.|посёлок|' as str FROM dual UNION
SELECT 'овраг' as code, 'овраг|' as str FROM dual UNION
SELECT 'городок' as code, 'городок|' as str FROM dual
)
SELECT t1.code, SUBSTR(t1.str,
DECODE(t2.lvl, 1, 1, INSTR(t1.str, '|', 1, t2.lvl - 1) + 1),
INSTR(t1.str, '|', 1, t2.lvl)
- DECODE(t2.lvl, 1, 1, INSTR(t1.str, '|', 1, t2.lvl - 1) + 1))
FROM test t1,
LATERAL (SELECT level AS lvl FROM dual
CONNECT BY NVL(INSTR(t1.str, '|', 1, level), 0) > 0) t2
;
WITH
str_csv AS (
SELECT 'проул.' as code, 'проул.|пр-к|' as str FROM dual UNION
SELECT 'ул.' as code, 'ул.|улица|ул-ца|' as str FROM dual UNION
SELECT 'пер.' as code, 'пер.|переулок|' as str FROM dual UNION
SELECT 'кв-л' as code, 'кв-л|квартал|' as str FROM dual UNION
SELECT 'линия' as code, 'линия|' as str FROM dual UNION
SELECT 'парк' as code, 'парк|' as str FROM dual UNION
SELECT 'рзд' as code, 'рзд|разъезд|' as str FROM dual UNION
SELECT 'сад' as code, 'Сад|' as str FROM dual UNION
SELECT 'тракт' as code, 'тракт|' as str FROM dual UNION
SELECT 'тер' as code, 'тер|территория|' as str FROM dual UNION
SELECT 'ст' as code, 'ст|станция|' as str FROM dual UNION
SELECT 'сл' as code, 'сл|слобода|' as str FROM dual UNION
SELECT 'пр-кт' as code, 'пр.|проспект|пр-кт|' as str FROM dual UNION
SELECT 'шоссе' as code, 'ш.|шоссе|' as str FROM dual UNION
SELECT 'пл' as code, 'пл|площадь|пл-дь|' as str FROM dual UNION
SELECT 'наб.' as code, 'наб.|набережная|наб-ая|' as str FROM dual UNION
SELECT 'тупик' as code, 'тупик|' as str FROM dual UNION
SELECT 'мост' as code, 'мост|' as str FROM dual UNION
SELECT 'пр.' as code, 'проезд|пр.|' as str FROM dual UNION
SELECT 'блв.' as code, 'блв.|бульвар|' as str FROM dual UNION
SELECT 'мкн.' as code, 'мкн.|микрорайон|' as str FROM dual UNION
SELECT 'пос.' as code, 'пос.|посёлок|' as str FROM dual UNION
SELECT 'овраг' as code, 'овраг|' as str FROM dual UNION
SELECT 'городок' as code, 'городок|' as str FROM dual
),
str_xml AS (
SELECT code, XMLType('<a><b>'||replace(str, '|','</b><b>')||'</b></a>') xml FROM str_csv
)
SELECT
code, extractValue(value(t),'b') str_type
FROM
str_xml s,
TABLE(XMLSequence(s.xml.extract('a/b'))) t
WHERE extractValue(value(t),'b') is not null
;
надо что бы при запросе вывел где status= true, и count_id = количество id за 30 дней.
|id|id_2|name|status|date| count_id |
|id|id_2|name|status|date| count_id |вывести не получится! т.к. группировать по полям |id|id_2|name| не имеет смысла, они могут быть уникальны и никакого COUNT за интервал не получится, например как считать количество в интервале для id=1,2,3 ... ??? это группироваться никак не будет вообще, будет выводиться построчно для каждого id и количество будет Всегда равно =1 и так для всех id. определитесь что вам надо?! конкретно
SELECT count(id) count_id
FROM tbl
WHERE status = 'true'
AND date >= now() - interval 30 day
;
-- дата начала
DECLARE @t_start AS DATETIME = DATEADD(minute, -7410, GETDATE());
-- дата конца
DECLARE @t_finish AS DATETIME = GETDATE();
-- разница между датами начала и конца в переменной типа DATETIME
DECLARE @t_diff AS DATETIME = @t_finish - @t_start;
-- разница между датами начала и конца
SELECT @t_diff;
SELECT DATEDIFF(second, DATEFROMPARTS(1900,1,1), @t_diff) / 3600.0 AS diff_h
SELECT
c.title,
ou.name,
m.text,
FROM_UNIXTIME(m.date) AS dt
FROM chat_users cu
INNER JOIN chat_users cuu ON cuu.chat_id = cu.chat_id AND cuu.user_id != cu.user_id
INNER JOIN users ou ON ou.id = cuu.user_id
INNER JOIN chat c ON c.id = cu.chat_id
INNER JOIN messages m ON m.user_id = cuu.user_id AND m.chat_id = cu.chat_id
WHERE cu.user_id = :ID_USER -- ID пользователя по которому выбирать чаты.
ORDER BY c.title ASC, m.date DESC
ALTER TABLE persons
ADD CONSTRAINT persons_check_rols CHECK (rols in('registrator', 'coordinator', 'user'));
SELECT
w.Id
,w.IMO
,v.Name
,w.loginManager
,um.Name AS managerName
,w.loginStorekeeper
,umk.Name AS storekeeperName
,w.Date
FROM Waybill w
INNER JOIN Vessel v ON w.IMO = v.IMO
INNER JOIN User um ON w.loginManager = um.Login
INNER JOIN User umk ON w.loginStorekeeper = umk.Login
ORDER BY w.Id
-- здесь я вынес параметры (домены, языки) в отдельное представление param,
-- которое определяется перед SELECT
-- это сделано, для того чтобы по всему запросу не искать и вписывать их
-- меняется все в одном месте:
WITH param AS (
SELECT
2 AS primary_domain_id, -- id первичного домена
1 AS secondary_domain_id, -- id вторичного домена
2 AS primary_language_id, -- id первичного языка
1 AS secondary_language_id -- id вторичного языка
FROM dual
)
SELECT *
FROM (
SELECT m.*,
row_number() over (
partition by m.movie_id
order by
case
when m.domain_id = p.primary_domain_id then 100
when m.domain_id = p.secondary_domain_id then 50
else 1
end DESC,
case
when m.language_id = p.primary_language_id then 100
when m.language_id = p.secondary_language_id then 50
else 1
end DESC
) rn
FROM `movie_desc` m, param p
WHERE (m.domain_id = p.primary_domain_id
OR m.domain_id = p.secondary_domain_id
OR m.domain_id IS NULL)
AND (m.language_id = p.primary_language_id
OR m.language_id = p.secondary_language_id
OR m.language_id IS NULL)
) t
WHERE t.rn = 1
;
SELECT
name,
sku,
CONCAT('https://домен/', IF(ua2.keyword IS NULL,'',CONCAT(ua2.keyword, '/')), IF(ua3.keyword IS NULL,'',CONCAT(ua3.keyword, '/')), IF(ua4.keyword IS NULL,'',CONCAT(ua4.keyword, '/')), ua1.keyword) AS url
FROM (
SELECT
name,
p.sku,
CONCAT( 'product_id=', p.product_id ) AS product_query,
CONCAT( 'category_id=', pc.category_id ) AS category_query,
CONCAT( 'series_id=', ps.series_id ) AS series_query,
CONCAT( 'subcategory_id=', psc.subcategory_id ) AS subcategory_query
FROM `oc_product_description` pd
LEFT JOIN oc_product p ON (p.product_id=pd.product_id)
LEFT JOIN oc_product_to_category pc ON (pc.product_id=p.product_id)
LEFT JOIN oc_product_to_series ps ON (ps.product_id=p.product_id)
LEFT JOIN oc_product_to_subcategory psc ON (psc.product_id=p.product_id)
WHERE p.date_available <= NOW()
AND p.status = '1'
) pd
LEFT JOIN oc_url_alias ua1 ON ( pd.`product_query` = ua1.`query` )
LEFT JOIN oc_url_alias ua2 ON ( pd.`category_query` = ua2.`query` )
LEFT JOIN oc_url_alias ua3 ON ( pd.`series_query` = ua3.`query` )
LEFT JOIN oc_url_alias ua4 ON ( pd.`subcategory_query` = ua4.`query` )
;