簡體   English   中英

SQL - 計算具有相同值的行數而不顯示計數

[英]SQL - Count number of rows with the same value without displaying the Count

如何計算 Selected 表中具有相同a.customer值的行數,但我不想顯示 Count,只是顯示 Selected 行並將顯示限制為 Count 中的前 3 個。 我有這樣的代碼:

    SELECT a.number, b.product, 
    x.descp, b.serial, a.customer
    FROM a 
    LEFT JOIN b
    ON a.number = b.number
    LEFT JOIN x
    ON b.product = x.product
    LEFT JOIN d
    ON a.stat = d.stat
    WHERE d.prmt = 'ABC'
    AND a.date >= 20210528
    AND a.date <= 20210530

您需要將計數和 ROW_NUMBER(僅在較新版本中可用)添加到孔 select

SELECT a.number, b.product, 
    x.descp, b.serial, a.customer
    FROM a 
    INNER JOIN (SELECT 
    a.customer, COUNT(*) countr, ROW_NUMBER() OVER( ORDER BY COUNT(*) DESC) rn
FROM
    a
        LEFT JOIN
    b ON a.number = b.number
        LEFT JOIN
    x ON b.product = x.product
        LEFT JOIN
    d ON a.stat = d.stat
WHERE
    d.prmt = 'ABC' AND a.date >= 20210528
        AND a.date <= 20210530
GROUP BY a.customer) t1 ON t1.customer = a.customer
    LEFT JOIN b
    ON a.number = b.number
    LEFT JOIN x
    ON b.product = x.product
    LEFT JOIN d
    ON a.stat = d.stat
    WHERE d.prmt = 'ABC'
    AND a.date >= 20210528
    AND a.date <= 20210530
    AND rn <= 3

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM