4

3つのSQLテーブルのデータを結合しようとしています。

表の形式は次のとおりです。

クライアント

╔════════╗
║ CLIENT ║
╠════════╣
║ A      ║
║ B      ║
║ C      ║
║ D      ║
╚════════╝

work_times

╔════════╦══════════╦════════╦════════════╗
║ Client ║   Work   ║ Amount ║    Date    ║
╠════════╬══════════╬════════╬════════════╣
║ A      ║ Web Work ║     10 ║ 2013-01-12 ║
║ B      ║ Research ║     20 ║ 2013-01-20 ║
║ A      ║ Web Work ║     15 ║ 2013-01-21 ║
║ C      ║ Research ║     10 ║ 2013-01-28 ║
╚════════╩══════════╩════════╩════════════╝

費用

╔════════╦══════════╦════════╦════════════╗
║ Client ║   Item   ║ Amount ║    Date    ║
╠════════╬══════════╬════════╬════════════╣
║ A      ║ Software ║     10 ║ 2013-01-12 ║
║ B      ║ Software ║     20 ║ 2013-01-20 ║
╚════════╩══════════╩════════╩════════════╝

各クライアントの作業と費用のカウントと合計を返すクエリが必要です。つまり、次のようになります。

╔════════╦═══════════╦═══════════╦══════════════╦══════════════╗
║ CLIENT ║ COUNTWORK ║ WORKTOTAL ║ COUNTEXPENSE ║ EXPENSETOTAL ║
╠════════╬═══════════╬═══════════╬══════════════╬══════════════╣
║ A      ║         2 ║        25 ║            1 ║           10 ║
║ B      ║         1 ║        20 ║            1 ║           20 ║
║ C      ║         1 ║        10 ║            0 ║            0 ║
╚════════╩═══════════╩═══════════╩══════════════╩══════════════╝

これまでのところ、私は次のものを持っています:

SELECT clients.Client,
 COUNT(distinct work_times.id) AS num_work,
 COUNT(expenses.id) AS num_expenses
FROM
 clients
 INNER JOIN work_times ON work_times.Client = clients.Client
   INNER JOIN expenses ON expenses.Client = work_times.Client
GROUP BY
  clients.Client

これは正しい方向に沿っているように見えますが、費用がかからないクライアントをスキップし、num_expensesにnum_workを掛けているようです。また、WHERE句を追加して、2つの日付の間の作業時間と経費のみを返すように指定したいと思います。目的の出力を取得するには、クエリにどのような変更を加える必要がありますか?

4

3 に答える 3

6

サブクエリの値を個別に計算する必要があります。最も外側のクエリの句の目的はWHERE、1つのテーブルに少なくともレコードがあるレコードを除外することです。したがって、この場合、Client Dは結果リストに表示されません。

SELECT  a.*,
        COALESCE(b.totalCount, 0) AS CountWork,
        COALESCE(b.totalAmount, 0) AS WorkTotal,
        COALESCE(c.totalCount, 0) AS CountExpense,
        COALESCE(c.totalAmount, 0) AS ExpenseTotal
FROM    clients A
        LEFT JOIN
        (
            SELECT  Client, 
                    COUNT(*) totalCount,
                    SUM(Amount) totalAmount
            FROM    work_times
            WHERE   DATE BETWEEN '2013-01-01' AND '2013-02-01'
            GROUP   BY Client
        ) b ON a.Client = b.Client
        LEFT JOIN
        (
            SELECT  Client, 
                    COUNT(*) totalCount,
                    SUM(Amount) totalAmount
            FROM    expenses
            WHERE   DATE BETWEEN '2013-01-01' AND '2013-02-01'
            GROUP   BY Client
        ) c ON a.Client = c.Client
WHERE   b.Client IS NOT NULL OR
        c.Client IS NOT NULL

アップデート

╔════════╦═══════════╦═══════════╦══════════════╦══════════════╗
║ CLIENT ║ COUNTWORK ║ WORKTOTAL ║ COUNTEXPENSE ║ EXPENSETOTAL ║
╠════════╬═══════════╬═══════════╬══════════════╬══════════════╣
║ A      ║         2 ║        25 ║            1 ║           10 ║
║ B      ║         1 ║        20 ║            1 ║           20 ║
║ C      ║         1 ║        10 ║            0 ║            0 ║
╚════════╩═══════════╩═══════════╩══════════════╩══════════════╝
于 2013-02-24T15:32:56.903 に答える
0

をサブクエリに移動できるため、ごとにすべてをgroup by繰り返す必要はありません。サブクエリを取得したら、両方に日付フィルタを簡単に追加できます。work_timeexpense

SELECT  clients.Client
,       work_times.cnt AS num_work
,       work_times.total AS total_work
,       expenses.cnt AS num_expenses
,       expenses.total AS total_expenses
FROM    clients
LEFT JOIN
        (
        SELECT  Client
        ,       COUNT(DISTINCT id) as cnt
        ,       SUM(Amount) as total
        FROM    work_times
        WHERE   Date between '2013-01-01' and '2013-02-01'
        GROUP BY
                Client
        ) work_times
ON      work_times.Client = clients.Client
LEFT JOIN
        (
        SELECT  Client
        ,       COUNT(DISTINCT id) as cnt
        ,       SUM(Amount) as total
        FROM    expenses
        WHERE   Date between '2013-01-01' and '2013-02-01'
        GROUP BY
                Client
        ) expenses
ON      expenses.Client = clients.Client
于 2013-02-24T15:31:19.163 に答える
0

ここでテストする適切なインスタンスはありませんが、おそらくそうして開始し、クエリをさらに改善できるかどうかを確認します...

select 
  T1.client, 
  ce AS 'Count Work', 
  am AS 'Work Total', 
  ci AS 'Count Expense', 
  am2 AS 'Expense Total' 
from (
  select 
    client, 
    count (work) as ce, 
    sum(amount) as am 
  FROM 
    clients 
      left join work_times 
      on fk_client=client 
  group by 
    fk_client
) T1 
left join (
  select 
    client, 
    count(item) as ci, 
    sum(amount) as am2 
  from 
    clients 
      left join expenses 
      on fk_client=client 
  group by fk_client
) T2 
where T1.client=T2.client;

これは非常に複雑に見えるかもしれませんが、クライアントごとに 1 つの行しかないことが保証されます。後でもっと読みやすくなるかもしれません...

于 2013-02-24T16:18:43.763 に答える