I am tracking when sellers sell below a certain price on a product on Amazon. I am storing products, sellers, and violations in the database. I am attempting to display the number of sellers who are violating within a 24 hour period. Rather than displaying the number of sellers violating, I am receiving the total number of violations.
ViolationsRepository.php
public function countNumberOfSellersInViolationsForVendorInLast24Hours($vendorId)
{
$select = "SELECT DISTINCT COUNT(
CASE
WHEN v.source = 'amazon' THEN
(SELECT DISTINCT s.id
FROM seller_info_amazon AS sai
LEFT JOIN sellers_amazon AS sa ON sa.amazon_id = sai.id
LEFT JOIN sellers AS s ON sa.seller_id = s.id
WHERE sai.unique_id = v.seller_id_amazon AND s.id IS NOT NULL
LIMIT 1)
WHEN v.source = 'ebay' THEN
(SELECT s.id
FROM sellers AS s
WHERE s.id = v.seller_id_ebay
LIMIT 1)
WHEN v.source = 'google' THEN
(SELECT s.id
FROM sellers AS s
WHERE s.id = v.seller_id_google
LIMIT 1)
END)
FROM
violations AS v
";
$timeLimit = new \DateTime('24 hours ago');
$where = " WHERE v.vendor_id = :vendorId AND v.last_scout_date >= :timeLimit \n";
$query = $this->getEntityManager()->getConnection()->prepare($select . $where );
$query->bindValue(':vendorId', $vendorId);
$query->bindValue(':timeLimit', $timeLimit->format("Y-m-d h:i:s"));
$query->execute();
return $query->fetchColumn();
}
sellers_amazon TABLE
seller_id amazon_id
violations TABLE
id vendor_id seller_id_amazon last_scout_date source
seller_info_amazon TABLE
id unique_id name
sellers TABLE
id originating_vendor_id name
Solved this - SELECT COUNT(DISTINCT ... instead of SELECT DISTINCT COUNT( ....
Related
I have a table called bids, that have multiple rows.
these all have unique IDs however they have a listingID as well, so everytime it inserts it inserts a new row but with that listingID.
I'm trying to only return one unique result for the ListingID as appose to all the bids in the table , I tried SELECT DISTINCT and group by, but both didn't seem to work.
At the moment this is printing all the records from the table 'bids'
I would like to only print the last record for the listingID column.
$bids = $this->db->query("SELECT bidID,listingID, listing_title, bid_date, username,amount, starting_, sold, vintage, bottles, size, cases, sold_date, bid_type,
FORMAT(`bin`, 0) AS `bin`,
(CASE
WHEN ( SELECT COUNT(*) FROM bids WHERE bid_listing = listingID )
THEN
(SELECT FORMAT(amount,0) FROM bids WHERE bid_listing = listingID ORDER BY bidID DESC LIMIT 1)
ELSE
FORMAT(`starting_`, 0)
END
) AS `starting`
FROM (`bids`)
JOIN listings ON listingID = bid_listing
JOIN users ON list_uID = userID
WHERE bidder_ID = $userID
ORDER BY bidID DESC");
Try this sql. I used b1.* because I don't know what fields you're trying to return.
$bids = $this->db->query("select b1.* from bids b1
left join bids b2 on (b1.listingID = b2.listingID and b1.bidID < b2.bidID
where b2.bidID is null");
$listSQL = "SELECT op.name as prodname,count(*) total
FROM oc_order_product op
INNER JOIN oc_order o ON op.order_id = o.order_id
INNER JOIN oc_product_to_category p2c ON op.product_id = p2c.product_id
INNER JOIN oc_category_description cd ON cd.category_id = p2c.category_id ";
$listSQL = $listSQL."where lower(cd.name) LIKE '%".$category_name."%'
AND YEAR(o.date_added) = '".$StartDate."'
AND o.order_status_id > '0' ";
$listSQL = $listSQL."GROUP BY op.name ORDER BY o.date_added ASC";
I have this query where i am displaying product names and count by year.
I want to display Product name, and for each product, show month and count for that month for that particular year.
for example for year 2015, show all 12 months and under which show count of products for that month.
Thanks
Your original query looks pretty close, but using non-grouped, non-aggregated fields "outside" a group by is usually not a good idea unless they came from a table whose full primary key was part of the group by list. That said, this should give you what you want.
SELECT op.name AS prodname
, YEAR(o.date_added) AS oYear
, MONTH(o.date_added) AS oMonth
, COUNT(DISTINCT o.order_id) AS numOfOrders
FROM ...
GROUP BY prodname, oYear, oMonth
ORDER BY prodname, oYear, oMonth
;
[...] being your original FROM and WHERE
Schema: http://pastebin.com/jU3HmmNM
$mainfetch = "SELECT * FROM status ORDER BY status_id DESC LIMIT 10,0";
while($mainfetch -> $result) {
$subquery = SELECT COUNT(*) FROM status s, likes l WHERE s.status_id = l.status_id AND l.member_id = 1;
$liked = $query->row();
if($liked > 0) {
//liked
}else {
//not liked
}
}
So this is not optimal as $subquery will execute each time 10 times, I wish to add $subquery to $mainfetch, how can I join them two?
You just need to add a left join on s.status_id = l.status_id... And then you get also the l.status_id: if it is null, then member 1 not liked it, otherwise yes of course.
Using the schema you provided:
SELECT s.status_id, s.text_id, count(l.status_id) as like_count
FROM status AS s LEFT JOIN likes AS l ON (s.status_id = l.status_id AND l.member_id = 1)
group by s.status_id, s.text_id
ORDER BY status_id DESC
LIMIT 10,0
I am attempting to count the number of new leads and the number of closed leads in any given month. The query below returns the month array correctly, but then only counts 1 if there are any leads or closes in the months, instead of the actual number that happened in that month. Any ideas what I am doing wrong?
query:
$productSql = "SELECT months.monthnum as monthnum, COUNT(contacts.lead_date) as lead_date_month, COUNT(contacts.close_date) as close_date_month, contacts.rep as rep
FROM months
LEFT JOIN contacts
ON months.monthnum = MONTH(contacts.lead_date)
AND months.monthnum = MONTH(contacts.close_date)
AND contacts.compid='$compid'
AND YEAR(contacts.lead_date) = '$year'
AND YEAR(contacts.close_date) = '$year'
AND contacts.rep = '$rep'
GROUP BY months.monthnum
ORDER BY months.monthnum ASC";
$productResult = mysql_query($productSql, $link) or die(mysql_error());
$label[] = $productRow['monthnum'];
$lead[] = $productRow['lead_date_month'];
$close[] = $productRow['close_date_month'];
};
echo "[".json_encode($label).",".json_encode($lead).",".json_encode($close)."]";
result:
[["January","February","March","April","May","June","July","August","September","October","November","December"],
["0","0","0","0","0","0","0","0","1","1","0","0"],
["0","0","0","0","0","0","0","0","1","1","0","0"]]
**Please don't chastise me for using mysql. I am dumping it as soon as this project is finished.
The way you build your JOIN condition you will get results only from records with MONTH(contacts.lead_date) = MONTH(contacts.close_date).
To fix that and to get your actual Count I would suggest splitting the statement into two queries:
SELECT
a.monthnum,
a.lead_date_month, b.close_date_month,
b.close_date_month / a.lead_date_month
FROM
(
-- Count number of new leads
SELECT
months.monthnum as monthnum,
COUNT(*) as lead_date_month,
contacts.rep as rep
FROM
months
LEFT JOIN contacts
ON
months.monthnum = MONTH(contacts.lead_date)
AND contacts.compid='$compid'
AND YEAR(contacts.lead_date) = '$year'
AND contacts.rep = '$rep'
GROUP BY
months.monthnum
ORDER BY
months.monthnum ASC
) as a
JOIN
(
-- Count number of closed leads
SELECT
months.monthnum as monthnum,
COUNT(*) as close_date_month,
contacts.rep as rep
FROM
months
LEFT JOIN contacts
ON
months.monthnum = MONTH(contacts.close_date)
AND contacts.compid='$compid'
AND YEAR(contacts.close_date) = '$year'
AND contacts.rep = '$rep'
GROUP BY
months.monthnum
ORDER BY
months.monthnum ASC
) as b
ON a.monthnum = b.monthnum
And MySQL isn't that bad. But MariaDB is better, you are right :-)
i am using this query to fetching products.the product table has 302,716 rows.it is taking too much time to execute around 2-3 minutes.but when i removed order by it takes less time.
SELECT DISTINCT
product.ProductID,
company.CompanyName
FROM
product
INNER JOIN company
ON company.CompanyID = product.CompanyID
LEFT JOIN company_csv_data
ON company.CompanyID = company_csv_data.CompanyID
LEFT JOIN productcategory
ON product.ProductID = productcategory.ProductID
LEFT JOIN category
ON category.CategoryID = productcategory.CategoryID
LEFT JOIN supplier
ON product.supplier = supplier.id
LEFT JOIN template_vouchers tm
ON product.ProductID = tm.voucher_id
WHERE company.turn_on = 1
AND product.ProductEndDate >= CURRENT_DATE
AND turn_off = 1
GROUP BY product.ProductID
ORDER BY clicks DESC,
product.CodeOpen DESC,
product.Online,
product.EntryDate DESC
LIMIT 0, 15
You could improve the query's speed/performance by creating indexes for the columns in the select and where clauses (this will slow down insert, delete and update statements..)