好的,所以我没有得到任何合法的错误或任何东西,但我试图得到它,以便我可以计算一个州在两个单独的表中列出的次数。我想要的所有状态都会出现,但我知道在某些状态下应该有多个值,但是每个COUNT值都会导致值为1.这是我能解决的问题吗?
SELECT shipping_address_state,
COUNT(shipping_address_state) OVER (PARTITION BY shopper_account_id)
FROM orders
WHERE shipping_address_country IN ('USA', 'Canada', 'Mexico')
UNION
SELECT vendor_state,
COUNT(vendor_state) OVER (PARTITION BY vendor_id)
FROM vendor
WHERE vendor_country IN ('USA', 'Canada', 'Mexico')
修改
所以我接受了一些建议,然后将其改为Union all。我还将DISTINCT添加到SELECT vendor_state和shipping_address_state部分。它现在摆脱了州名列中的所有重复,但计数仍然是1.如果没有DISTINCT关键字,重复的状态会显示,但是作为单独的数据行(如宾夕法尼亚州将显示3次,但每个计数为1)。这就是现在的样子。有人知道为什么COUNT关闭了吗?
SELECT DISTINCT vendor_state "State",
COUNT(vendor_state) OVER (PARTITION BY vendor_id) "Count"
FROM vendor
WHERE vendor_country IN ('USA', 'Canada', 'Mexico')
UNION ALL
SELECT DISTINCT shipping_address_state "State",
COUNT(shipping_address_state) OVER (PARTITION BY shopper_account_id) "Count"
FROM orders
WHERE shipping_address_country IN ('USA', 'Canada', 'Mexico')
修改
有趣的是,我解决了COUNT问题的很大一部分。我只是改变了PARTITION BY子句,这样它就可以实现PARTITION BY。现在它们被正确计算,但由于它们位于两个表中,因此State列中仍然存在重复值。每个列只计算它在该表中仅显示的次数。我尝试将它改回UNION而不是UNION ALL,但它并没有改变任何东西。让我们看看是否可以做到这一点!
SELECT DISTINCT vendor_state "State",
COUNT(vendor_state) OVER (PARTITION BY vendor_state) "Count"
FROM vendor
WHERE vendor_country IN ('USA', 'Canada', 'Mexico')
UNION ALL
SELECT DISTINCT shipping_address_state "State",
COUNT(shipping_address_state) OVER (PARTITION BY shipping_address_state) "Count"
FROM orders
WHERE shipping_address_country IN ('USA', 'Canada', 'Mexico')
ORDER BY "State"
答案 0 :(得分:1)
更改UNION
UNION ALL
UNION
从结果集中删除重复的行。
但UNION ALL
显示结果集。
因此,在使用UNION ALL
而不是UNION
答案 1 :(得分:0)
您应该将UNION更改为UNION,还要为count列设置一个名称,如下所示:
SELECT shipping_address_state,
COUNT(shipping_address_state) OVER (PARTITION BY shopper_account_id) cnt
FROM orders
WHERE shipping_address_country IN ('USA', 'Canada', 'Mexico')
UNION ALL
SELECT vendor_state,
COUNT(vendor_state) OVER (PARTITION BY vendor_id) cnt
FROM vendor
WHERE vendor_country IN ('USA', 'Canada', 'Mexico')