SQLazy Cuts Wasted Work on Complex SQL by 90% For you who wrestle with SQL every day

  • 01Pain points and Vision
  • 02What Is SQLazy
  • 03AI Collaboration and Back-Translation
  • 04Application Architecture
  • 05Use Case Deep Dive
  • 06Real-world Examples

Let's talk shop for a second: Is this still how you write SQL?

From nested logic to cross-database compatibility, from debugging and troubleshooting to legacy handoffs, do these development headaches sound all too familiar?

Brain-twisting logic, maze-like nesting

Business requirements keep piling on. SQL nesting balloons to seven or eight layers. Logic turns into a tangled mess. Even the author can't read their own code. Execution keeps throwing surprises.

Endless debugging, draining effort

Tracking down errors means breaking subqueries apart layer by layer, running and re-running validation checks. Debugging often takes longer than writing the code – and that's brutally inefficient.

Cross-database compatibility, reinventing the wheel

The same business logic needs to be adapted to different syntaxes – MySQL, Oracle, PostgreSQL, and more. It's pure grunt work, and it drives maintenance costs way up.

Legacy handoffs, defusing bombs

You inherit the legacy SQL – no comments, no docs, logic so tangled it's unreadable. It feels like defusing an unknown bomb: no one dares touch it, afraid one small change will ripple through the whole system and bring it down.

Tickets piling up, slow to respond

Data query and extraction tickets pile up, with average response time of 3-5 days. Without real-time data, agile decision-making and fast iteration are out of reach.

What ideal SQL development actually looks like?

Writing SQL should feel this good: freed from tedious, repetitive labor – back to the true nature of building logic.

01 Clear logic

Logic broken down into steps. Each one single-purpose. Logic stays linear, clear.

02 Debug fast

Check intermediate results anytime. One click to locate the error source. Debugging cycles shrink.

03 Worry-free cross-database

One set of core logic. Automatically adapted across databases. No manual syntax rewrites.

04 Easy handoffs

Logic comes with built-in visual docs and comments. New hires can pick it up with zero communication overhead.

05 AI-human cooperation

AI handles the boilerplate. The core business logic stays yours.

  • 01Pain points and Vision
  • 02What Is SQLazy
  • 03AI Collaboration and Back-Translation
  • 04Application Architecture
  • 05Use Case Deep Dive
  • 06Real-world Examples

What is SQLazy: AI doesn't write SQL, it compiles SQL

SQLazy in one sentence – define logic in the standardized natural language, compile it deterministically into native SQL.

Write step-by-step execution logic, the SPEC, in standardized natural language. A deterministic compiler, not a probabilistic AI model, compile it into native, executable SQL with 100% accuracy. This is the paradigm shift: from generative AI to compiled engineering.

You define the logic

Runs entirely on the explicit logic you define – you keep the wheel, start to finish.

Deterministic, controllable results

A deterministic compiler generates the final SQL. Stable. Reproducible. No uncertainty.

Output purely native SQL

The final output is standard, clean native SQL – embeddable in any database environment, with zero intrusion.

Capability 1: Break down nested SQL into plain language-steps

No more nested layers. Complex business logic becomes an intuitive, linear, step-by-step workflow.

Core breakdown: reduce requirements to atomic operations.
Filter
Sort
Summarize
Join
Rank
Segment

Clear, linear logic

One step, one operation. Write it as you think. Read it without peeling back layers.

Easy to learn and understand

Complex logic broken into simple steps - no guesswork. Plug and play.

Iterate freely. Maintain easily

When requirements change, edit only the relevant steps - each is isolated, no ripple effect across the rest.


Calculate longest consecutive up-days

SQL

WITH s2 AS (
    SELECT CODE, DT, CL FROM stock WHERE CODE = 110838
)
SELECT MAX(consecutive up-days) AS longest consecutive up days
FROM (
    SELECT No-gain Flag, COUNT(DT) AS consecutive up-days
    FROM (
        SELECT CODE, DT, CL,
            SUM(CASE WHEN CL < col__3 THEN 1 ELSE 0 END) OVER (
                ORDER BY CASE WHEN DT IS NULL THEN 1 ELSE 0 END, DT ASC
            ) + 1 AS No-gain Flag
        FROM (
            SELECT s2.*, LAG(CL) OVER (
                ORDER BY CASE WHEN DT IS NULL THEN 1 ELSE 0 END, DT ASC
            ) AS col__3
            FROM s2
        ) sub__4
    ) s3
    GROUP BY No-gain Flag
) s4					

SQLazy

Name Anchor Statement
s1 stock filter CODE = 110838
s2 sort DT asc
s3 segment CL down as NoRisingDays
s4 summarize DT count as ContinuousDays group NoRisingDays
summarizesummarize ContinuousDays max as max_ContinuousDays

Capability 2: Debug step by step, check intermediate results as you go – find bugs 10x faster

No more manual SQL breakdown, every step's result is checkable - data debugging becomes as clear and controllable as code development.

Real-time intermediate result preview

Click any step to view the full intermediate table – no manual breakdown and execution.

Pinpoint the error source

Whether it's a filter condition gone wrong or a flaw in the calculation logic, you can pinpoint the problem on the spot.

Quantum leap in debugging efficiency

Borrowing proven logic from code debugging, this upgrades the old “guess-and-check” process into a visual, traceable, efficient workflow.

No more inefficient cycles. Ever.

No more “thirty minutes to write, an hour to debug”. Just building and optimizing the logic that matters.


Capability 3: One set of logic, compiled for every database

Write logic once. It auto-adapts to every database dialect – seamless cross-platform development.

One-click target database switch

One logic layer. Touch nothing in the core code. Switch databases in one click.

Full-stack support for mainstream platforms

Native support for mainstream databases — MySQL, Oracle, PostgreSQL, and more – plus data warehouse platforms like Hive, Spark, and Snowflake.

Automatically handles syntax details

Automatically handles function differences, data type conversions, and window function quirks across databases.

No more grunt work

No more writing N SQL versions of one business logic just to fit N databases. That era's over.


Multi-database support, one-click compilation

Automatically masks dialect differences – seamless switching

Capability 4: Logic is the living document – code turns into an asset, easy to hand down

The steps you write are the living document – every line of logic, clearly visible and fully traceable.

Self-documenting

The list of steps is itself a clear description of the computation –- no need to write separate, cumbersome comments. Logic and explanation fuse naturally.

Code turns into an asset

Ad-hoc tickets become a workflow of standardized steps. The historical logic stops being opaque, and reuse means tuning a few key parameters.

Easy to understand

Whether it's a new hire takeover or tracing back through the logic later, reading the visualized step-by-step workflow is enough to fully grasp the business logic fast.

Knowledge preserved

Core business logic gets locked into living documents – turnover stops meaning knowledge loss. New hires inherit the best practices directly.

  • 01Pain points and Vision
  • 02What Is SQLazy
  • 03AI Collaboration and Back-Translation
  • 04Application Architecture
  • 05Use Case Deep Dive
  • 06Real-world Examples

AI assistance: SQLazy's force multiplier

AI assistance: Only translates syntax, never claims the logic

AI is the professional typist – not the decision-maker on business logic. Technology serves thought; it doesn't replace it.

Step 1 – Plain language description

Flexible plain-language step description(e.g.: Get data where CODE is 110838)

Step 2 – Plain-to-Standardized conversion

AI converts plain language into standardized statements(e.g.: filter (CODE is 110838))

Step 3 – Compile to SQL

The compiler generates executable SQL.

AI focuses only on converting plain-language descriptions into standardized, structured workflows – strictly avoiding subjective logic design.

Works alongside the AI coding tool: AI plans, the engine executes

Works with AI coding tools like Claude or Codex to get the most out of SQLazy.

AI as the brain: structures fuzzy problems

Understands requirements, clarifies ambiguity, and breaks down business logic – turning fuzzy plain-language requirements into a structured, step-by-step script draft. This is where AI's core strength in handling unstructured information pays off.

Knowledge base driven: rules inherited automatically

Deploy a global spec file at the project root, defining table structure, output format, and hard constraints. AI automatically loads and inherits all rules on startup to ensure that code stays compliant.

Structured four-step output: Process is auditable

Forces AI to output in four steps: capability inventory → requirement breakdown → function matching → code implementation. The reasoning behind every step stays visible – the logic is traceable, human-auditable, and refuses to be a black box.

Proactively clarifies boundaries: avoids assumption risk

When requirements are fuzzy, AI proactively asks clarifying questions on boundaries – date range definitions, null-handling rules, grouping-key uniqueness. No default assumptions. Logical deviation gets stopped at the source.

Collaboration effect: from blind box to controllable engineering

Manually writing SQL

Logic readability: Multi-layer nested structures are hard to read. Logic stays opaque, hidden inside individual developers' coding habits – new hires can't get up to speed quickly.

Debugging and maintenance: Manual breakdown of complex nested subqueries needed. Historical code has no docs to lean on – every iteration and maintenance cycle burns disproportionate time and manpower.

Multi-database compatibility: Cross-database compatibility means manual rewriting – repetitive, inefficient labor. The result depends entirely on individual skill, and stays highly prone to syntax and logic errors.

Ordinary AI SQL tools

Logic readability: AI-generated logic runs wild with no fixed standard — output is uncontrollable, and the reasoning process turns into a black box, with no way to trace the logic's source or judge whether it holds up.

Debugging and maintenance: The generation process is a black box – when errors happen, there's no way to trace the cause. Code becomes unmaintainable, closed off to long-term iteration and reuse.

Compatibility and reliability: AI hallucinations exist – output stays inconsistent, cross-database compatibility is weak, and neither the accuracy nor security of business logic can be guaranteed.

AI + SQLazy collaboration

Logic readability: Step-by-step logic stays clear and transparent, visualized into standard SQL structure – unified, traceable, and easy for any team member to pick up.

Debugging and maintenance: Every step can be independently validated and traced back – errors get pinpointed exactly. The steps themselves are living document, so maintenance and iteration stay cheap.

Compatibility and reliability: Compile-level validation guarantees 100% correctness. One-click, automatic switching across databases. AI hallucinations are eliminated entirely – business runs on stable ground.

Core strength: AI + SQLazy combines AI's speed with the control of hand-written code — a more transparent, more reliable model for database development.

Back-translate complex legacy SQL: breathe new life into legacy code

Turns AI's semantic understanding of SQL into a SQLazy script that's both readable as document and compilable as executable code – the shift from “code black box" to "maintainable asset." It fully revives the team's accumulated technical legacy, solving the legacy-system maintenance problem at the root.

Pain point 1: Code black box

Legacy SQL is deeply nested and its logic is opaque. Once the original developers leave, no one dares touch it — and it becomes a hot potato for system maintenance.

Pain point 2: AI interpretation limits

Relying on AI alone yields a static doc. It can't keep pace as the SQL iterates – the doc drifts out of sync with the code and loses its value as a reference.

Pain point 3: AI modification risk

AI-rewritten SQL easily drifts from the original business rules. Logical consistency can't be guaranteed, and pushing it straight to production carries serious business risk.

Back-translation workflow

From legacy SQL to maintainable asset: The complete workflow

01 Legacy SQL entry

Ingest complex SQL scripts, in multiple dialects, as the source for back-translation.

02 AI semantic parsing

Break down nested queries and implicit logic, and identify how calculation rules relate to business metrics.

03 Generate a step-by-step script

Generate a structured SQLazy script that turns black-box logic into a readable workflow.

04 Human review and validation

Domain experts review the logic to ensure the script matches the business requirements.

05 Small-sample verification

Compare old and new outputs on test data to verify logical and data consistency.

06 Compile to native SQL

Compile the verified script into native SQL for the target database.

07 Closed-loop asset maintenance

Future changes start from the SQLazy script, forming a closed-loop asset that is reusable and traceable.

Closed-Loop Asset Management
  • 01Pain points and Vision
  • 02What Is SQLazy
  • 03AI Collaboration and Back-Translation
  • 04Application Architecture
  • 05Use Case Deep Dive
  • 06Real-world Examples

Application Architecture

Native SQL only. No embedded code in the production system. Zero architectural risk.

A desktop IDE that's easy to pick up

Step-level editing

Edit workflow steps visually, with built-in syntax highlighting and smart assistance. Writing scripts takes far less skill to get started.

Result preview

Click any step to see its intermediate result instantly. Risk-free trial and error for development and debugging.

SQL compilation

Compile in real time to native SQL, and switch target databases such as MySQL or PostgreSQL with one click.

LLM configuration

Plug in any LLM API key to help standardize your SQL queries.

Runs entirely locally. Zero data leakage.

Runs entirely locally. Data never leaves your internal network. Works fully offline. Enterprise data security is built in at the source.

Private LLMs, Unlimited AI assistance.

Connect to your enterprise's in-house LLM service. No call limits for AI code suggestions and optimization. Costs under control, responses faster.

Built-in engine. Debug on millions of rows.

Built-in SPL computing engine. Process million-row datasets locally with ease. Logic verification is far faster than on a traditional database.


Enterprise-Grade Security and Deployment

Secure, controlled, efficient SQL development for large enterprises and organizations. Full protection for your data assets and business compliance.

01 Fully on-premises deployment

The platform's core services can be deployed inside its internal network, achieving physical isolation and control. External access risk is eliminated at the source, which meets the data localization requirements of heavily regulated sections such as finance and government.

02 End-to-End closed loop within the internal network

All AI analysis, debugging and compilation of SQL code happens inside the enterprise's internal network. No data is transmitted over the public internet, which removes risks such as data leakage and MITM attacks and keeps core business data secure.

03 Compatibility with Chinese LLM ecosystems

Deeply compatible with mainstream Chinese LLMs, and integrates seamlessly with privately deployed models. Fits the requirements of Xinchuang (IT application innovation) initiative, providing technological self-reliance and security compliance together.

04 Non-intrusive, seamless integration

No runtime components are installed in the production system;, no changes to the existing databases and application architecture. Plugs into the current development setup quickly, protects business continuity at zero risk, and makes development more efficient.

  • 01Pain points and Vision
  • 02What Is SQLazy
  • 03AI Collaboration and Back-Translation
  • 04Application Architecture
  • 05Use Case Deep Dive
  • 06Real-world Examples
Ticket

SQLazy is built for data query tickets

Bottlenecks in traditional data ticket handling

Efficiency bottlenecks

Requests pile up in the queue. Average turnaround runs 3-5 days, too slow to support timely decisions.

Maintenance bottlenecks

No one can quickly make sense of a 200-line production SQL query. Handoffs and maintenance become a disaster.

Cost bottlenecks

Staff time is eaten up by tedious, repetitive SQL writing, senior talent can't focus on deep analysis and strategic insight.

Ticket

SQLazy's Core Value in Ticket Handling

Fast turnaround

Fixes the hassle of AI-driven SQL writing and difficulty of debugging it, and responds business needs fast.

Correctness

Step-by-step debugging ensures correct results and makes auditing easy.

Ad-hoc queries

Generate ad-hoc queries fast, without preparing complex test cases for the AI.

Helps understand business logic

Business users can see each step of the logic and validate it directly, creating efficient interaction.

Handoff-ready assets

The logic behind each ticket is automatically captured as a reusable asset, so team experience keeps building and improving over time.

Ticket

Ticket asset library: Make every ticket count

From one-off labor to reusable assets: building lasting digital productivity for your team.

Every delivery builds the asset

Ticket scripts are archived with business tags and metric definitions, turning the results into traceable, auditable digital assets.

AI-powered search and reuse

For a new request, find a matching historical script, adjust it, and deliver. No reinventing the wheel.

Team experience continuity

New hires learn standard scripts and metric definitions from the asset library and get up to speed fast, so technical experience passes down seamlessly.

Continuous iteration and optimization

Scripts in the asset library are continuously refined and distilled into team best practices, steadily improving overall efficiency and data quality.


01 10X efficiency gain

02 100% quality improvement

03 60% cost reduction

Migration

SQLazy: For database migration scenarios

Existing migration approaches

Approach 1: Compatibility mode

✔ Pros

Needs almost no rework and goes live fast. Best suited to TP workloads with simple SQL.

✘ Cons

Limited compatibility coverage; weak support for AP workloads with complex syntax. Parsing on the fly makes performance unstable.

Approach 2: AI rewriting

✔ Pros

Generates native SQL for the target database, making full use of its capabilities.

✘ Cons

LLMs hallucinate, and their SQL is highly error-prone when logic is complex, so human review becomes expensive.

Migration

SQLazy solution: The AI-powered path from logic to asset

Lower cost. Higher efficiency. 100% logic fidelity.

AI understanding and translation

Use AI to turn complex SQL into structured SPEC scripts.

Human review and validation

Run one step at a time and check each result, so the logic is exactly right.

SQLazy compilation and output

Compile the SPEC script precisely into native SQL for the target database.


Higher efficiency

Automated testing handles error checking and review, cutting the migration cycle by more than 50%.

Lower cost

The structured steps are easy to debug and audit, which significantly cuts labor costs.

Asset capture

Turn SQL into reusable, maintainable logic assets for enterprises.

Migration

SQLazy+SPL: Post-migration performance assurance

Some SQL can suffer a sharp drop in performance after migration, and optimizing the SQL alone doesn't fix it.
SQLazy's core engine, SPL, can implement more high-performance algorithms, delivering a 10x performance gain.

  • 01Pain points and Vision
  • 02What Is SQLazy
  • 03AI Collaboration and Back-Translation
  • 04Application Architecture
  • 05Use Case Deep Dive
  • 06Real-world Examples

Real-world examples

01Event-triggered cumulative sum reset
Source data:
ID Date Invoiced Amount
AAA 2023-01 0 10
AAA 2023-02 0 15
AAA 2023-03 1 15
AAA 2023-04 0 10
AAA 2023-05 0 10
AAA 2023-06 1 10
BBB 2022-05 0 40
BBB 2022-06 1 20
BBB 2022-07 0 30
BBB 2022-08 1 30
Target result:
ID Date Invoiced Amount
AAA 2023-03 1 40
AAA 2023-06 1 30
BBB 2022-06 1 60
BBB 2022-08 1 60

Keep only the invoiced rows (invoiced=1). In each row, Amount is the cumulative sum since the last invoice.

SQLazy implementation:
Name Anchor Command
t1 invoice sort id,dt desc
t2 compute invoiced cum as grp partition id
t3 summarize dt max as dt invoiced max as invoiced amount sum as amount group id grp
t4 derive id dt invoiced amount
Compiled SQL(MySQL):
WITH invoice_groups AS (
	SELECT id, dt, invoiced, amount,
    	SUM(invoiced) OVER (PARTITION BY id ORDER BY CASE WHEN id IS NULL THEN 1 ELSE 0 END, id ASC, dt DESC ROWS UNBOUNDED PRECEDING) AS grp
  	FROM invoice
),
aggregated AS (
  	SELECT id, grp, MAX(dt) AS dt, MAX(invoiced) AS invoiced, SUM(amount) AS amount
  	FROM invoice_groups
  	GROUP BY id, grp
)
SELECT id, dt, invoiced, amount
FROM aggregated
ORDER BY id, grp

02Session numbering by time gap
account_number dt seq
19 2024-04-03 07:02:02 1
19 2024-04-03 07:02:41 2
19 2024-04-03 14:58:49 1
19 2024-04-03 19:58:49 1
19 2024-04-05 14:58:49 1
19 2024-04-05 14:59:31 2
19 2024-04-17 23:56:13 1
19 2024-04-18 00:15:13 2
19 2024-04-18 14:56:13 1
19 2024-04-19 07:41:55 1
19 2024-04-19 07:42:20 2
19 2024-04-19 08:41:20 3
20 2024-04-17 23:59:13 1
20 2024-04-18 07:41:55 1
20 2024-04-18 19:41:55 1
20 2024-04-18 19:56:55 2

Generate a sequence number (Seq) based on the first two columns:

  • Partition by account and process each partition by dt in ascending order.
  • If the time gap between the current row's event time and the previous row's is more than 1 hour, reset the sequence number to 1.
  • Otherwise (time gap ≤ 1 hour),increment the sequence number by 1.
SQLazy implementation:
Name Anchor Command
t1 numEvents sort account_number asc dt asc
t2 segment condition ((dt[-1] elapse 3600 second) <= dt) partition account_number as grp
t3 compute # as seq partition account_number grp
Compiled SQL(MySQL):
WITH t1 AS (
  SELECT account_number, dt FROM numEvents
),
t2 AS (
  SELECT account_number, dt,
    1 + SUM(CASE WHEN (col__5 + INTERVAL 3600 SECOND <= dt) THEN 1 ELSE 0 END)
      OVER (PARTITION BY account_number ORDER BY account_number ASC, dt ASC) AS grp
  FROM (
    SELECT t1.*,
      LAG(dt) OVER (PARTITION BY account_number ORDER BY account_number ASC, dt ASC) AS col__5
    FROM t1
  ) sub__6
)
SELECT
  ROW_NUMBER() OVER (PARTITION BY account_number, grp ORDER BY account_number ASC, dt ASC) AS seq,
  dt,
  account_number
FROM t2
ORDER BY account_number ASC, dt ASC

03Conditional partitioning
Source data:
ID SPLIT CUST DATE AMOUNT
ID_1 SPLIT_YES A 2024-05-01 00:00:00 100
ID_1 SPLIT_NO A 2024-04-01 00:00:00 200
ID_1 SPLIT_YES B 2024-03-01 00:00:00 50
ID_2 SPLIT_YES A 2024-05-01 00:00:00 50
ID_2 SPLIT_NO A 2024-04-01 00:00:00 300
ID_2 SPLIT_NO B 2024-03-01 00:00:00 300
ID_3 SPLIT_YES B 2024-04-01 00:00:00 90
ID_3 SPLIT_NO B 2024-04-01 00:00:00 30
ID_3 SPLIT_NO A 2024-04-01 00:00:00 10
ID_3 SPLIT_NO A 2024-03-01 00:00:00 10
Target result:
ID SPLIT CUST DATE AMOUNT
ID_1 SPLIT_NO A 2024-04-01 00:00:00 200
ID_1 SPLIT_YES A 2024-05-01 00:00:00 150
ID_2 SPLIT_NO A 2024-04-01 00:00:00 600
ID_2 SPLIT_YES A 2024-05-01 00:00:00 50
ID_3 SPLIT_NO A 2024-04-01 00:00:00 20
ID_3 SPLIT_NO B 2024-04-01 00:00:00 30
ID_3 SPLIT_YES B 2024-04-01 00:00:00 90

Partition the table by ID and SPLIT. Within each partition, if any dates are duplicated, partition further by CUST. Then sum the amounts and keep the record with the latest date.

SQLazy implementation:
Name Anchor Command
t2 splitAcc rank DT desc dense as rnk partition ID SPLIT
t3 compute if (rnk = 1 then CUST else null) as rnk1 partition ID SPLIT
t4 compute AMOUNT sum as total_amount rnk1 icount as num_cust partition ID SPLIT
t5 compute AMOUNT sum as total_cust_amount partition ID SPLIT CUST
t6 compute if (num_cust = 1 then total_amount else total_cust_amount) as amt
t7 filter rnk = 1
derive ID SPLIT CUST DT amt
Compiled SQL(MySQL):
WITH ranked AS (
  SELECT
    sub__13.*,
    DENSE_RANK() OVER (PARTITION BY ID, SPLIT ORDER BY DT DESC) AS rnk
  FROM splitAcc sub__13
),
with_totals AS (
  SELECT
    ID, SPLIT, CUST, DT, AMOUNT, rnk,
    CASE WHEN rnk = 1 THEN CUST ELSE NULL END AS rnk1,
    SUM(AMOUNT) OVER (PARTITION BY ID, SPLIT) AS total_amount,
    COUNT(DISTINCT CASE WHEN rnk = 1 THEN CUST ELSE NULL END) OVER (PARTITION BY ID, SPLIT) AS num_cust,
    SUM(AMOUNT) OVER (PARTITION BY ID, SPLIT, CUST) AS total_cust_amount
  FROM ranked
)
SELECT
  ID, SPLIT, CUST, DT,
  CASE WHEN num_cust = 1 THEN total_amount ELSE total_cust_amount END AS amt
FROM with_totals
WHERE rnk = 1

04Fill missing numeric values by rule
Invoices
InvoiceID Amount ProjectID
1 100.0000 1
2 100.0000 2
3 100.0000 3
4 100.0000 4
Projects
ID ProjectID AccountCode
1 1 12345
2 2 12345
3 2 7890
4 3 800
5 3 234
6 3 987
7 4 800
8 4 234
9 4 987
10 4 2579
Target result:
InvoiceID Amount ProjectID AccountCode SplitAmount
1 100.0 1 12345 100.0
2 100.0 2 12345 50.0
2 100.0 2 7890 50.0
3 100.0 3 800 33.34
3 100.0 3 234 33.33
3 100.0 3 987 33.33
4 100.0 4 800 25.0
4 100.0 4 234 25.0
4 100.0 4 987 25.0
4 100.0 4 2579 25.0

Join the two tables, split each project's invoice amount evenly across its accounts, and round each share to two decimal places. Give the last account the remainder so the total stays unchanged.

SQLazy implementation:
Name Anchor Command
t1 numEvents join projectid; with invoices; projectid; take invoiceid amount
t2 sort accountcode asc
t3 compute invoiceid count as cnt, round (amount /cnt, 2) as splitamount partition projectid
t4 compute splitamount sum as saa, if (# = 1 then round (splitamount + amount - saa,2) else splitamount) as f1 partition projectid
t5 derive invoiceid amount accountcode projectid f1 as splitamount
t6 sort invoiceid asc accountcode asc
Compiled SQL(MySQL):
WITH joined AS (
  SELECT p.id, p.projectid, p.accountcode, i.invoiceid, i.amount
  FROM projects p
  LEFT JOIN invoices i ON p.projectid = i.projectid
),
with_count AS (
  SELECT *,
    COUNT(invoiceid) OVER (PARTITION BY projectid) AS cnt
  FROM joined
),
with_split AS (
  SELECT *,
    ROUND(amount / cnt, 2) AS splitamount
  FROM with_count
),
with_sum AS (
  SELECT *,
    SUM(splitamount) OVER (PARTITION BY projectid) AS saa
  FROM with_split
),
adjusted AS (
  SELECT *,
    CASE
      WHEN ROW_NUMBER() OVER (PARTITION BY projectid ORDER BY accountcode ASC) = 1
      THEN ROUND(splitamount + amount - saa, 2)
      ELSE splitamount
    END AS f1
  FROM with_sum
)
SELECT invoiceid, amount, accountcode, projectid, f1 AS splitamount
FROM adjusted
ORDER BY invoiceid ASC, accountcode ASC

What you care about most: how hard is it to learn?

Get the hang of it in half a day, with your existing habits kept. Learning stays light and efficient.

Extremely simple core concepts. Up to speed in no time.

Fewer than 20 basic operations that carries over your familiar SQL core concepts. Only syntax changes, and it's more intuitive.

Real-world example library

Multiple real-world business examples across industries. You don't have to build from scratch to get started.

Work with what you already have. Not to replace it.

It doesn't ask you to give up your SQL skills. It offers a more efficient way to organize the logic.

Fit seamlessly into the way you are working

The final output is native SQL that runs directly on your existing databases and BI tools. It's fully compatible with any data platform.

How to get started: No barrier to entry

Try it now. No waiting for deployment. We offer multiple ways to fit different use cases.

Web version: Open and go, quick to evaluate

No sign-up or login needed. Open your browser and start using SQLazy. It's a good fit for quick validation and generating ad hoc queries.

Desktop IDE version: Debug locally, no limits on features

Debug on large local datasets, and connect your organization's in-house LLMs and private knowledge bases, so data processing stays more secure.

Seamless integration: Work with your whole toolchain

Generates native SQL you can copy and paste straight into any query editor, job scheduler, or BI tool.

Seamless integration: Keep working the way you do

No intrusion on your existing data architecture, and full respect for how your team works and the tech stack you use. AI becomes an invisible assistant inside your workflow.

We look forward to making SQL development simpler, together with you.

Try it online

Try SQLazy online now at www.sqlazy.com . No signup needed. Every core feature is free to use.

Feedback and suggestions

If you have any problems or ideas for improvement, feel free to contact us through SQLazy community forum or by email. We look forward to your feedback.