0

表 (userData) 如下所示:

userId    property    value
1         AGE         28
1         GENDER      M
2         AGE         28
2         GENDER      F
3         AGE         29
3         GENDER      F
4         AGE         29
4         GENDER      F

所以我想得到类似的东西:

Gender    Age    Count
M         28     1
F         28     1
F         29     2
4

3 回答 3

1

像这样的东西?

SELECT
    ud1.value AS gender,
    ud2.value AS age,
    COUNT(*) AS c
FROM userData ud1
JOIN userData ud2 ON
    ud1.userId = ud2.userId AND
    ud2.property = 'AGE'
WHERE ud1.property = 'GENDER'
GROUP BY gender, age
于 2013-03-13T02:50:41.743 回答
0
-- Not tested
SELECT *
  FROM userData age INNER JOIN
       userData gender ON gender.userId = age.userId
 WHERE age.property = 'AGE'
   AND gender.property = 'GENDER'

你会得到

userId    property    value   userId    property    value   
1         AGE         28      1         GENDER      M
2         AGE         28      2         GENDER      F
3         AGE         29      3         GENDER      F
4         AGE         29      4         GENDER      F

完成后,您可以 COUNT() (未测试):

  SELECT age.value, gender.value, COUNT(*)
    FROM userData age INNER JOIN
         userData gender ON gender.userId = age.userId
   WHERE age.property = 'AGE'
     AND gender.property = 'GENDER'
GROUP BY age.value, gender.value
于 2013-03-13T02:48:39.047 回答
0
SELECT  Gender, Age, COUNT(*) TotalCount
FROM
        (
            SELECT  UserID,
                    MAX(CASE WHEN property = 'Gender' THEN value END) Gender,
                    MAX(CASE WHEN property = 'Age' THEN value END) Age
            FROM    tableName
            GROUP   BY UserID
        ) s
GROUP   BY Gender, Age

输出

╔════════╦═════╦════════════╗
║ GENDER ║ AGE ║ TOTALCOUNT ║
╠════════╬═════╬════════════╣
║ M      ║  28 ║          1 ║
║ F      ║  28 ║          1 ║
║ F      ║  29 ║          2 ║
╚════════╩═════╩════════════╝
于 2013-03-13T02:51:39.570 回答