[英]SQL use COUNT (and GROUP BY?) to perform calculation in a SELECT without excluding records
我有一個測試數據庫,設置如下:
CREATE TABLE summary (
row_sid SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
product_list_sid INT,
amount INT,
qty INT
);
CREATE TABLE list_header (
product_list_sid INT
);
CREATE TABLE list_detail (
product_list_sid INT,
product_sid INT
);
CREATE TABLE product (
product_sid SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
product_description VARCHAR(60)
);
INSERT INTO product(product_description) VALUES ("can"), ("bottle");
INSERT INTO list_detail VALUES (1,1), (1,1), (1,2), (2,1), (2,2),(2,2),(2,1);
INSERT INTO list_header VALUES (1), (2);
INSERT INTO summary(product_list_sid, amount, qty) VALUES (1,3,9), (1,15,45), (2,12,36);
我編寫了一個查詢以連接所有表,這樣我就可以得到匯總表中包含的所有產品的分解列表,以及匯總中的“金額”和“數量”值。 到目前為止做得很好...
查詢:
SELECT row_sid, product_description, amount, qty
FROM summary
INNER JOIN list_header ON summary.product_list_sid = list_header.product_list_sid
INNER JOIN list_detail ON list_header.product_list_sid = list_detail.product_list_sid
INNER JOIN product ON list_detail.product_sid = product.product_sid;
結果:
row_sid product_description amount qty
1 can 3 9
2 can 15 45
1 can 3 9
2 can 15 45
1 bottle 3 9
2 bottle 15 45
3 can 12 36
3 bottle 12 36
3 bottle 12 36
3 can 12 36
現在,我想修改該查詢,以將“金額”和“數量”值除以共享相同row_sid的行數。
因此,在此示例中,row_sid為“ 1”或“ 2”的每一行將具有1/3的“金額”和“數量”值,而row_sid為“ 3”的每一行將具有1/4的“金額”和“數量”值。
理論上將產生下表:
row_sid product_description amount qty
1 can 1 3
2 can 5 15
1 can 1 3
2 can 5 15
1 bottle 1 3
2 bottle 5 15
3 can 3 9
3 bottle 3 9
3 bottle 3 9
3 can 3 9
我已經做到了這一點:
SELECT row_sid, product_description, amount / COUNT(row_sid) AS amount, qty / count(row_sid) AS qty
FROM summary
INNER JOIN list_header ON summary.product_list_sid = list_header.product_list_sid
INNER JOIN list_detail ON list_header.product_list_sid = list_detail.product_list_sid
INNER JOIN product ON list_detail.product_sid = product.product_sid
GROUP BY row_sid;
產生:
row_sid product_description amount qty
1 can 1 3
2 can 5 15
3 can 3 9
這樣可以正確計算,但是GROUP BY刪除了我需要的所有其他行。 但是,沒有GROUP BY,我離目標還很遠。
我想念什么?
似乎您需要在查詢和相同查詢的組結果的計數之間進行聯接。
如果您僅使用group by的查詢,則沒有所有行,因為group by ...對數據進行“分組”,因此,為了避免group by的這種行為,您可以將原始查詢與匯總的查詢合並,例如:
SELECT s.row_sid, product_description, amount/t.my_count, qty/t.my_count
FROM summary s
INNER JOIN list_header ON summary.product_list_sid = list_header.product_list_sid
INNER JOIN list_detail ON list_header.product_list_sid = list_detail.product_list_sid
INNER JOIN product ON list_detail.product_sid = product.product_sid
INNER JOIN (
SELECT row_sid, COUNT(row_sid) my_count
FROM summary
INNER JOIN list_header ON summary.product_list_sid = list_header.product_list_sid
INNER JOIN list_detail ON list_header.product_list_sid = list_detail.product_list_sid
INNER JOIN product ON list_detail.product_sid = product.product_sid
GROUP BY row_sid;
) t on t.row_sid = s.row_sid
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.