兩個表的SQL查詢我有兩個表:具有參考鍵
Discounts(disid primary key)
Cust(custid primary key, disid ref discount(disid))
現在我需要一個查詢來獲取custid
讓所有disid
(優惠券),並且客戶可以包含相同disid
不止一次。
兩個表的SQL查詢我有兩個表:具有參考鍵
Discounts(disid primary key)
Cust(custid primary key, disid ref discount(disid))
現在我需要一個查詢來獲取custid
讓所有disid
(優惠券),並且客戶可以包含相同disid
不止一次。
select custid, count(distinct disid) from cust
group by custid
having count(*) = (select count(*) from discounts)
SELECT COUNT(DISTINCT D.disid) FROM CUST C
INNER JOIN DISCOUNTS D ON D.disid=C.disid GROUP BY D.disid
嘗試這兩種解決方案:
SELECT a.custid, COUNT(a.disid) totalCoupon
FROM cust a
INNER JOIN discounts b
ON b.disid = a.disid
GROUP BY a.custid
或
SELECT a.custid, COUNT(a.disid) totalCoupon
FROM cust a
INNER JOIN discounts b
ON b.disid = a.disid
GROUP BY a.custid
HAVING COUNT(a.disid) > 1 -- customers having the same (but more than 1)
-- CouponID will only be shown here
一個簡單的加入不會做呢?如果沒有更多的信息需要 – 2012-08-04 14:48:49