简体   繁体   中英

SQL count the number of rows based on multiple column value

I have a table as shown below. How do I write the SQL code if I want to count the number of times the row (eg X = A, Y = Burger) appear and return as Z? Thanks

Select * X, Y 
from DataBase

Results:

X   Y           Z(to be determined..)
--------------------
A   Burger      2
A   Burger      2
A   Fries       1
B   Burger      2
B   Pie         1
B   Burger      2
C   Pie         2
C   Pie         2
C   Burger      1
.   .           .
.   .           .
.   .           .

You can do:

select X,Y,count(*) from Table group by X,Y

You are looking for a window function:

select t.*, count(*) over (partition by x, y) as z
from DataBase t;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM