我有一个表格书籍
NAME
A
B
C
和另一本书籍分配
ID ASSIGNMENTTEXT
1 Book.Assigned.To:A
2 Book.Assigned.To:A
3 Book.Assigned.To:B
4 Book.Assigned.To:B
5 Book.Assigned.To:C
6 Book.Assigned.To:A
7 OtherText:A
我想知道为每个人分配了多少本书,例如
我应该
Person Bookcount
A 3
B 2
C 1
我只想通过Book.Assigned.To:NAME
获取这些行我尝试过使用子字符串,但我无法解决
谢谢,
艾登
答案 0 :(得分:1)
您可以使用内部联接和分组
select a.Name, b.count(*)
from Books a
inner join Booksassignment b on b.ASSIGNMENTTEXT like concat('%:', a.NAME)
group by a.Name
答案 1 :(得分:0)
如果name列的长度始终为1,则可以如下所示:
SELECT
B.Name AS Person,
COUNT(1) Bookcount
FROM
Books B INNER JOIN
Booksassignment BA ON B.NAME = BA.RIGHT(ASSIGNMENTTEXT, 1)
GROUP BY
B.Name
答案 2 :(得分:0)
试试这个:
;WITH T AS
(
SELECT
Id,
REPLACE(AssignmentText,SUBSTRING(AssignmentText,0, CHARINDEX(':',AssignmentText,0)+1),'') AS AssignedName
FROM @tblBooksassignment
)
SELECT
B.Name,
COUNT(T.Id) AS 'PersonBookCount'
FROM T
INNER JOIN @tblBooks B ON B.Name=T.AssignedName
GROUP BY B.Name
<强>输出:强>
答案 3 :(得分:0)
CREATE TABLE #T(nAME varchar(25))
INSERT INTO #T
SELECT 'A' UNION ALL
SELECT 'B' UNION ALL
SELECT 'C'
CREATE TABLE #tt (Id int,Book Varchar(25),Name Varchar(255))
INSERT INTO #tt
SELECT 1,'Book.Assigned','A' UNION ALL
SELECT 2,'Book.Assigned','A' UNION ALL
SELECT 3,'Book.Assigned','B' UNION ALL
SELECT 4,'Book.Assigned','B' UNION ALL
SELECT 5,'Book.Assigned','C' UNION ALL
SELECT 6,'Book.Assigned','A'
SELECT #tt.Name,COUNT(#tt.Name) from #tt INNER JOIN #T
ON #t.Name=#tt.Name
GROUP BY #tt.Name
答案 4 :(得分:0)
我觉得这样的事情会起作用
SELECT B.NAME,
COUNT( * ) as Bookcount
FROM Books B
JOIN Booksassignment BA
ON B.NAME = SUBSTRING( BA.ASSIGNMENTTEXT, -1 )
AND BA.ASSIGNMENTTEXT LIKE 'Book.Assigned.To:%'
GROUP BY B.NAME
答案 5 :(得分:0)
如果名称在ASSIGNMENTTEXT
列的末尾,则使用right
函数
select name, count(*) from Books b
inner join Booksassignment a on b.name like RIGHT(a.ASSIGNMENTTEXT, 1)
where ASSIGNMENTTEXT like 'Book.Assigned.To:%'
group by name
更新答案 如果你需要第一列是&#34; Book.Assigned.To:&#34;:
select ASSIGNMENTTEXT, count(*) from Books b
inner join Booksassignment a on b.name like RIGHT(a.ASSIGNMENTTEXT, 1)
where ASSIGNMENTTEXT like 'Book.Assigned.To:%'
group by ASSIGNMENTTEXT
例:
with Books as (select * from ( select 'A' as name union select 'B' union select 'C' ) as b )
, Booksassignment as (
select * from (
select 1 as iD, 'Book.Assigned.To:A' ASSIGNMENTTEXT union
select 2, 'Book.Assigned.To:A' union
select 3, 'Book.Assigned.To:B' union
select 4, 'Book.Assigned.To:B' union
select 5, 'Book.Assigned.To:C' union
select 6, 'Book.Assigned.To:A'
) as c
)
select name, count(b.name) as ASSIGNMENTs from Books b
inner join Booksassignment a on b.name like RIGHT(a.ASSIGNMENTTEXT, 1)
group by name
答案 6 :(得分:0)
我在Mysql上试了一下:
SELECT CONCAT(SUBSTRING(o.ASSIGNMENTTEXT,-1),&#39;&#39;,COUNT(ASSIGNMENTTEXT
))FROM Booksassignment
AS o GROUP BY ASSIGNMENTTEXT
< / p>