SQL Server Add only one row of a particular column to a count/group by query

2w3kk1z5  于 2023-08-02  发布在  其他
关注(0)|答案(2)|浏览(156)

Raw data:
| Category | Serial Number |
| ------------ | ------------ |
| Sports | 3462 |
| Sports | 4373 |
| Sports | 3453 |
| Auto | 7742 |
| Auto | 1247 |
| Auto | 3463 |
| Auto | 1242 |
| Auto | 7746 |

My goal with select query is to get that data looking like this:

CategorySerial Number CountExample Serial Number
Sports33462
Auto47742

My current query:

SELECT
   Category,
   COUNT( [Serial Number] ) AS [Serial Number Count]
FROM
    abcDB
GROUP BY
    Category

The above query has everything aside from that last column where I just need ONE of the serial numbers from each category as an example. It doesn't matter which serial number it is as long as it falls into the correct category.

Can someone please edit my query so it includes a column like this? Thank you.

pcrecxhr

pcrecxhr1#

Please try the following solution.

Window function ROW_NUMBER() is very handy for such scenario.

SQL

-- DDL and sample data population, start
DECLARE @tbl TABLE (Category VARCHAR(20),Serial_Number VARCHAR(10));
INSERT @tbl (Category, Serial_Number) VALUES
('Sports', '3462'),
('Sports', '4373'),
('Sports', '3453'),
('Auto', '7742'),
('Auto', '1247'),
('Auto', '3463'),
('Auto', '1242'),
('Auto', '7746')
-- DDL and sample data population, end

;WITH rs AS
(
    SELECT *
        , ROW_NUMBER() OVER (PARTITION BY Category ORDER BY @@spid) AS seq
        , COUNT(*) OVER (PARTITION BY Category ORDER BY @@spid) AS cnt
    FROM @tbl
)
SELECT Category, Serial_Number, cnt
FROM rs
WHERE seq = 1;

Output

CategorySerial_Numbercnt
Auto77425
Sports34623
yvfmudvl

yvfmudvl2#

The following might work if you were to return a random row in a group

CREATE TABLE abcDB (
    Category VARCHAR(20),
    Serial_Number INT
);

INSERT INTO abcDB (Category, Serial_Number)
VALUES
    ('Sports', 3462),
    ('Sports', 4373),
    ('Sports', 3453),
    ('Auto', 7742),
    ('Auto', 1247),
    ('Auto', 3463),
    ('Auto', 1242),
    ('Auto', 7746);

WITH main_table AS (
  SELECT
    Category,
    Serial_Number AS Example_Serial_Number,
    COUNT(*) OVER (PARTITION BY Category) AS Serial_Number_Count,
    DENSE_RANK() OVER (PARTITION BY Category ORDER BY Serial_Number) AS ranking
  FROM abcDB
)

SELECT
  Category,
  Serial_Number_Count,
  Example_Serial_Number
FROM main_table
WHERE ranking = FLOOR(RAND()*(Serial_Number_Count-1+1)+1);
CategorySerial_Number_CountExample_Serial_Number
Auto51247
Sports33462

fiddle

相关问题