2

我有 3 个表(一个持有结果/投票,两个是查找表)如下:

投票

areaid    - which links to an area table to get area name
townid    - which links to a town table to get town name
votingyn  - if a person is voting or not (Y or N)

考虑上表具有以下测试数据:

1,2,'Y'
1,3,'N'
2,1,'Y'
3,3,'N'

.. 等等,areid 倍数,townid 倍数,当然还有一个 Y 或 N 如果投票

所以..我正在尝试找到获得以下结果的最有效方法:

按 areaid 分组,获得不同的 townid 计数以及有多少 Y 或 N 投票(如果 areadid 和 townid 连接到名称的查找表):

area 1,     town1,       voting Y,   voting N
-------------------------------------------------
AREA 1      TOWN 1       23          12
AREA 2      TOWN 2       15          7

不确定这是否足够清楚..任何帮助都非常感谢!

4

1 回答 1

5

这样的事情应该这样做(未经测试):

SELECT a.Name AS 'Area', t.Name AS 'Town',
  SUM(CASE v.votingyn WHEN 'Y' THEN 1 ELSE 0 END) AS 'Yes'
  SUM(CASE v.votingyn WHEN 'N' THEN 1 ELSE 0 END) AS 'No'
FROM VOTES AS v
  JOIN TOWN AS t ON v.townid = t.id
  JOIN AREA AS a ON v.areaid = a.id
GROUP BY (a.Name, t.Name)
于 2012-05-30T21:26:16.860 回答