我有一個PSQL查詢,其中左側的AND參數加入到另一個表格下面的檢查表示例中。LEFT加入PSQL,其中AND參數在另一個表上
發票
id | account | invoice_date | reference | total_amount | status
-----+---------+-------------------------+-----------+--------------+--------
164 | 100 | 2016-08-03 03:05:08.996 | 161 | 2000.00 |
165 | 100 | 2016-08-03 21:42:07.865 | 164 | 0 |
167 | 100 | 2016-08-03 22:56:41.731 | 166 | 100.00 |
168 | 100 | 1970-01-01 00:33:20 | 161 | 200 |
169 | 100 | 2016-08-08 00:00:00 | 161 | 200 |
Invoice_items
id | invoice | invoice_item_type | product | quantity | unit_price | reference | amount
-----+---------+-------------------+---------+----------+------------+-----------+---------
143 | 164 | 1 | 6 | | | 161 | 2000.00
144 | 165 | 1 | 11 | | | 164 | 0
145 | 167 | 1 | 8 | | | 166 | 100.00
也有另一種表的產品,但只有相關領域有ID
這是我的查詢
select products.id, sum(invoice_items.amount) as total_revenue
from products
left join invoice_items on invoice_items.product = products.id
left join invoices on invoice_items.invoice = invoices.id
and invoices.invoice_date= current_date
group by products.id;
我需要查詢的是列出所有Product ID並在total_revenue列中放置產品的銷售總額(在'product'字段類似的invoice_items表中添加'amount')當前日期(找到在INVOICES表上)。但是當我運行這個查詢時,它列出了產品的所有total_amounts。我錯過了什麼?
樣品輸出。 8,6和11必須爲空
id | total_revenue
-----+---------------
125 |
154 |
119 |
129 |
8 | 100.00
112 |
5 |
132 |
104 |
113 |
143 |
152 |
121 |
127 |
165 |
139 |
146 |
15 |
2 |
147 |
149 |
166 |
169 |
13 |
106 |
122 |
9 |
11 | 0
110 |
120 |
130 |
155 |
134 |
136 |
101 |
168 |
131 |
157 |
161 |
103 |
150 |
159 |
107 |
108 |
145 |
4 |
12 |
158 |
167 |
138 |
162 |
100 |
156 |
163 |
124 |
123 |
109 |
153 |
102 |
105 |
151 |
116 |
133 |
140 |
160 |
148 |
126 |
141 |
7 |
118 |
10 |
164 |
128 |
14 |
144 |
135 |
1 |
6 | 2000.00
3 |
137 |
117 |
142 |
111 |
你的意思是_8,6和11必須是空的。既然你在'left join'中有'和'這個日期,它會加回那些不匹配的產品。查看你的查詢,如果你只想要有產品的收入,那麼即使是內連接也是足夠的。 – Neeraj