1

How to count primary key of one table which is used in another table in 5 to 6 column?

If table1 has primary key srno which is used in table2 in column d1, d2, d3, d4.

I want to count how many times srno=1,2,3,4... etc used in table2.

Does anyone know how to do that???

4

2 回答 2

1

以下查询将返回 table2 中的 d1、d2、d3 和 d4 列中每个值使用的次数(已更新):

SELECT table1.srno, SUM(cnt) FROM
  table1,
  (SELECT d1 AS srno, COUNT(d1) AS cnt FROM table2 GROUP BY d1
   UNION ALL
   SELECT d2 AS srno, COUNT(d2) AS cnt FROM table2 GROUP BY d2
   UNION ALL
   SELECT d3 AS srno, COUNT(d3) AS cnt FROM table2 GROUP BY d3
   UNION ALL
   SELECT d4 AS srno, COUNT(d4) AS cnt FROM table2 GROUP BY d4) AS cnt_tbl
WHERE table1.srno = cnt_tbl.srno
GROUP BY table1.srno

在这里尝试小提琴

如果您只计算一个特定的主键(例如 1),请尝试

SELECT SUM(cnt) FROM
  (SELECT COUNT(*) AS cnt FROM table2 WHERE d1 = 1
   UNION ALL
   SELECT COUNT(*) AS cnt FROM table2 WHERE d2 = 1
   UNION ALL
   SELECT COUNT(*) AS cnt FROM table2 WHERE d3 = 1
   UNION ALL
   SELECT COUNT(*) AS cnt FROM table2 WHERE d4 = 1) AS cnt_tbl

在这里拉小提琴。

或者没有 UNION 的更优雅的解决方案:

SELECT SUM(cnt) FROM
  (SELECT ((d1=1) + (d2=1) + (d3=1) + (d4=1)) AS cnt 
   FROM table2 
   WHERE d1 = 1 OR d2= 1 OR d3 = 1 OR d4 = 1) AS cnt_tbl

小提琴

于 2013-05-28T10:12:21.703 回答
0

尝试:

SELECT COUNT(PK_COL1_NAME_IN_TABLE2) FROM TABLE2

请参阅文档

于 2013-05-28T09:57:49.793 回答