我有2个桌子,我想计算出行次数。
tbl1
id location
1 A
2 B
3 C
tabl 2
id tabl1id table1id
1 1 2
2 1 3
3 2 1
4 3 1
5 1 3
6 1 3
我想要这样的结果,我想算一下
SrNo A To B A to C B To A C To A
1 1 3 1 1
答案 0 :(得分:0)
这可能有助于你...
DECLARE @tbl1 TABLE
(
id INT , location VARCHAR(1)
)DECLARE @tbl2 TABLE
(
id INT , tabl1id INT , table1Toid INT
)
INSERT INTO @tbl1
SELECT 1 , 'A' UNION ALL
SELECT 2 , 'B' UNION ALL
SELECT 3 , 'C'
INSERT INTO @tbl2
SELECT 1 , 1, 2 UNION ALL
SELECT 2 , 1 , 3 UNION ALL
SELECT 3 , 2 , 1 UNION ALL
SELECT 4 , 3 , 1 UNION ALL
SELECT 5 , 1 , 3 UNION ALL
SELECT 6 , 1 , 3
SELECT * FROM
(
SELECT COUNT(tabl1id) CNT , (SELECT location FROM @tbl1 WHERE ID=T2.tabl1id)+' To '+(SELECT location FROM @tbl1 WHERE ID=T2.table1Toid) AS location
FROM @tbl2 T2
GROUP BY tabl1id,table1Toid
)D
PIVOT (MIN(CNT) FOR location IN ([B To A],[C To A],[A To B],[A To C])) AS PVT
答案 1 :(得分:0)
如果要查看行(而不是列)中的结果,您可以通过按两列分组来完成此操作:
SELECT src , dest, count(id)
FROM tbl2
GROUP BY src , dest
了解更多信息,请参阅MySQL GROUP BY two columns